[英]Iteratively change every cell in a column of a Pandas dataframe
我正在嘗試更改Pandas數據框中每個單元格的值。 期望.loc
允許我使用范例df.loc[row_index, column_name] = cell value
來標識一個單元df.loc[row_index, column_name] = cell value
,我使用了以下循環:
table["field"] = 6 #placehodler value used only to create the column
for field, index in enumerate(table["field"]): table.loc[index,
"field"] = table.loc[index, "field_x"] if math.isnan(table.loc[index,
"field_y"]) else table.loc[index, "field_y"]
但是,出現以下錯誤: KeyError: 'the label [6] is not in the [index]'
。 通過索引選擇值的正確語法是什么?
您不應使用enumerate
來生成索引和列值,而應使用iterrows
。
用法示例:
In [6]:
df = pd.DataFrame({'a':np.arange(5), 'b':np.random.randn(5)})
df
Out[6]:
a b
0 0 -0.579585
1 1 -0.582196
2 2 -0.367147
3 3 -0.363332
4 4 0.880826
In [9]:
for index, row in df.iterrows():
print('index: ', index)
print('row: ', row)
輸出:
index: 0
row: a 0.000000
b -0.579585
Name: 0, dtype: float64
index: 1
row: a 1.000000
b -0.582196
Name: 1, dtype: float64
index: 2
row: a 2.000000
b -0.367147
Name: 2, dtype: float64
index: 3
row: a 3.000000
b -0.363332
Name: 3, dtype: float64
index: 4
row: a 4.000000
b 0.880826
Name: 4, dtype: float64
這將允許您使用df.loc[index]
訪問特定的行,如果需要這些列,則可以使用上述for
循環中的row.index
進行訪問
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.