我正在嘗試通過 pandas 資料框撰寫一個回圈,該回圈采用當前行中特定列(16:20)的平均值(忽略 NaN)并將其附加到串列中(我稍后想在我的資料框中創建一個新列)。我的代碼如下:
import numpy as np
n = 0
list = []
for row in df:
list.append(
np.nanmean(
df.iloc[n, 16:20]
)
)
n = 1
len(list)
>>> 87
len(df)
>>> 20434
如您所見,for 回圈在 86 次回圈后停止 - 為什么會停止?我不應該收到一個包含 20434 個條目的串列嗎?
uj5u.com熱心網友回復:
使用for n, row in enumerate(df):,但它顯然不是最好的解決方案!
更喜歡:
out = df.iloc[:, 16:20].mean(axis=1) # Remember 20 is excluded in Python
uj5u.com熱心網友回復:
您必須使用索引:
list = []
for index in df.index:
list.append(
np.nanmean(
pd.to_numeric(df.iloc[index, 16:20])
)
)
len(list)
>>> 20434
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/488461.html
上一篇:向資料框添加條件列
下一篇:用R中從負到正的數字線填充向量
