if语句基于索引子集 - pandas dataframe

时间:2017-07-29 00:39:09

标签: python pandas

我有一个列表,其中包含我的数据帧中的索引值子集。如果数据帧索引在该列表中并且其他地方没有(''),我想返回值(x)。我尝试了下面的表达式而没有结果。

df.loc[indexList]['Col'] = 'x'

你能告诉我如何使它工作以及为什么上面的例子没有?

1 个答案:

答案 0 :(得分:0)

你有警告吗?当你犯这个错误时,Pandas有时会打印一个SettingWithCopyWarning。

此代码已损坏:

df.loc[indexList]['Col'] = 'x'

因为df.loc[indexList]会返回一个副本,然后您可以修改并放弃该副本。

相反,请尝试:

df.loc[indexList, 'Col'] = 'x'

然后你不会“得到”而是“设置”indexList子集的结果,这样可以避免复制数据。