![](/img/trans.png)
[英]How do I find the index for the minimum, second to minimum, etc. in a multi-dimensional list in Python?
[英]In pure python (no numpy, etc.) how can I find the mean of certain columns of a two dimensional list?
我目前使用 CSV 閱讀器來創建一個二維列表。 首先,我去掉標題信息,所以我的列表純粹是數據。 遺憾的是,有幾列是文本(日期等),有些僅用於檢查其他數據。 我想做的是取這些數據的某些列並獲得平均值。 其他列我只需要忽略。 我有哪些不同的方法可以做到這一點? 我可能不關心速度,我在閱讀了 csv 之后做了一次,我的 CSV 文件可能有 2000 行左右,只有 30 列左右。
這是假設所有行的長度相等,如果不是,您可能需要添加一些 try / except case
lst = [] #This is the rows and columns, assuming the rows contain the columns
column = 2
temp = 0
for row in range (len(lst)):
temp += lst [row][column]
mean = temp / len (lst)
為了測試元素是否是數字,在大多數情況下,我使用
try:
float(element) # int may also work depending on your data
except ValueError:
pass
希望這可以幫助; 我無法測試此代碼,因為我正在使用手機。
嘗試這個:
def avg_columns(list_name, *column_numbers):
running_sum = 0
for col in column_numbers:
for row in range(len(list_name)):
running_sum += list_name[row][col]
return running_sum / (len(list_name)*len(column_numbers))
您將列表的名稱和列的索引(從 0 開始)傳遞給它,它將返回這些列的平均值。
l = [
[1,2,3],
[1,2,3]
]
print(avg_columns(l, 0)) # returns 1.0, the avg of the first column (index 0)
print(avg_columns(l, 0, 2)) # returns 2.0, the avg of column indices 0 and 2 (first and third)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.