[英]Pandas: Not able to set a cell value based on a condition on other column
我有一个 dataframe 如下:
ID Score Bid_Doc_ID
1 67 3
2 -1 2
3 -1 7
我想将Bid_Doc_ID
字段设置为 -1 其中Score
== -1
为此,我使用以下代码:
df = df.loc[df['Score']==-1,'Bid_Doc_ID']=-1
我收到以下错误:
AttributeError: 'int' object has no attribute 'loc'
即使我尝试过:
df = df.loc[df['Score'].astype(str)==-1,'Bid_Doc_ID']=-1
仍然得到同样的错误。
我的预期结果:
ID Score Bid_Doc_ID
1 67 3
2 -1 -1
3 -1 -1
这个问题似乎很微不足道,但有些我错过了一些东西!
尝试删除分配新df
的代码部分:
df = df.loc[df['Score']==-1,'Bid_Doc_ID']=-1 # change
df.loc[df['Score']==-1,'Bid_Doc_ID']=-1 # to be this
或者,另一种选择是,您可以使用np.where
获得所需的东西?
import numpy as np
df['Bid_Doc_ID'] = np.where(df['Score'] == -1, -1, df['Bid_Doc_ID'])
当您运行df = df.loc[df['Score'].astype(str)==-1,'Bid_Doc_ID']=-1
时,看起来您用 integer 或 boolean 覆盖了您的 df (这就是为什么'int' object has no attribute 'loc'
错误)。 尝试检查 df 的值来验证这一点。
如果您在适当的位置修改 DF 会发生很多事情,这绝不是一个好主意,最好将修改后的 dataframe 分配给一个新变量,例如df_fixed
,它会为您节省大量调试时间,甚至更糟,发布生产中的错误。
试试下面的,不是太简洁,但是它使用纯pandas方法和方法链接,这是这几天推荐的方式。
bid_doc_id_fixed = df.apply(lambda x: -1 if x['Score'] == -1 else x['Bid_Doc_ID'], axis=1)
df_fixed = df.assign(Bid_Doc_ID=bid_doc_id_fixed)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.