我想根据另一列的值更改一列的值。例如,给定以下 DF:
Freq TOC
1 10 NA
2 20 NA
3 30 NA
for index, row in df.iterrows():
if row["Freq"] == 20:
row["TOC"] = True
我希望:
Freq TOC
1 10 NA
2 20 True
3 30 NA
但是什么都没有改变。怎么了?谢谢。
最佳答案
pd.DataFrame.iterrows
为 Python 级循环中的每一行返回一个系列,而不是指向数据框的动态链接。更高效的是,您可以使用列式矢量化方法而不是行式循环(假设您对 1 == True
感到满意):
df['TOC'] = np.where(df['Freq'] == 20, True, np.nan)
更惯用的是分配一个 bool 系列,即仅True
/False
值:
df['TOC'] = df['Freq'] == 20
什么是在你的循环中使用索引,虽然这会很低效:
for index, row in df.iterrows():
if row['Freq'] == 20:
df.loc[index, 'TOC'] = True
关于python - Pandas 数据框 : Why I can't change the value of one column based on value of another through row iteration?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53464071/