Python - 不等長列表的列求和
什麼是列求和
列求和指的是計算資料集或矩陣中每一列的值之和的過程。在資料分析或數值計算的背景下,列求和是用於沿垂直軸彙總和分析資料的常用操作。
例如,考慮一個以表格形式表示的資料集,其中包含行和列。每一列對應一個變數或特徵,每一行對應一個觀測值或資料點。列求和涉及將每一列中的值加起來,以獲得每個變數的單個總和。讓我們用一個例子來說明這一點。
假設我們有以下資料集,表示五個人在三次不同測量中的身高(以釐米為單位)。
| 測量 1 | 測量 2 | 測量 3 | |
| 0 | 170 | 175 | 180 |
| 1 | 165 | 168 | 172 |
| 2 | 180 | 182 | 178 |
| 3 | 172 | 169 | 171 |
| 4 | 175 | 176 | 174 |
要計算列求和,我們必須將每一列中的值加起來。
列求和
測量 1:862
測量 2:870
測量 3:875
在這種情況下,列求和提供了每次測量的總高度,使我們能夠概覽每個變數中的累積值。
當您擁有不等長的列表並希望在 Python 中計算每一列的列總和時,我們可以使用不同的方法。以下列出了三種實現此目的的方法。
使用迴圈和填充列表
在這種方法中,我們可以迴圈遍歷列表並對每一列的值求和,同時考慮列表的長度可能不同。我們需要用零填充較短的列表以使其長度相等。
示例
在此示例中,我們首先使用`max(len(lst) for lst in lists)`找到所有列表中的最大長度。然後,我們使用列表推導式用零填充每個列表以匹配最大長度。填充後,我們可以使用`zip(*padded_lists)`轉置列表,最後,我們使用另一個列表推導式計算列總和。
lists = [
[1, 2, 3],
[4, 5],
[6, 7, 8, 9]
]
max_length = max(len(lst) for lst in lists)
padded_lists = [lst + [0] * (max_length - len(lst)) for lst in lists]
column_sum = [sum(col) for col in zip(*padded_lists)]
print("The column summation of uneven sized lists:",column_sum)
輸出
The column summation of uneven sized lists: [11, 14, 11, 9]
使用 Itertools.zip_longest() 函式
來自 `itertools` 模組的`zip_longest`函式允許我們將不等長列表壓縮在一起,並用指定預設值(在本例中為 0)填充缺失的值。
示例
在此示例中,`zip_longest(*lists, fillvalue=0)`用填充壓縮列表,然後我們使用列表推導式計算列總和,這與之前的方法類似。
from itertools import zip_longest
lists = [
[1, 2, 3],
[4, 5],
[6, 7, 8, 9, 10]
]
column_sum = [sum(col) for col in zip_longest(*lists, fillvalue=0)]
print("The column summation of uneven sized lists:",column_sum)
輸出
The column summation of uneven sized lists: [11, 14, 11, 9, 10]
使用 NumPy
NumPy提供了一種優雅的方法來處理不等長列表,而無需顯式填充。即使列表長度不同,它也會自動廣播列表以執行求和操作。
示例
在此示例中,我們使用`np.array(lists)`將列表列表轉換為 NumPy 陣列,其中每一行表示一個列表。然後,我們使用`np.sum(arr, axis=0)`沿第一個軸(即行)計算總和,這有效地為我們提供了列總和。
import numpy as np
lists = [
[1, 2, 3],
[4, 5],
[6, 7, 8, 9]
]
arr = np.array(lists, dtype=object )
column_sum = np.sum(arr, axis=0)
print("The column summation of uneven sized lists:",column_sum)
輸出
The column summation of uneven sized lists: [1, 2, 3, 4, 5, 6, 7, 8, 9]
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP