df.loc[df['A'] == 1]['B'] = 2
出现的问题:赋值没有起作用
前面引用方式会有下面的警告,链接里明确说明这种引用方式是不允许的
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
iloc._setitem_with_indexer(indexer, value)
正确的应该是
df.loc[df['A']==1,'B'] = 2
一个注意点:
用 DataFrame/Series 给 df 的A列赋值,如果 A 列和 DataFrame/Series 的 index 不一样,是不能赋值成功的
这个时候可以这也赋值
df.loc[df['A'] == 1]['B'] = list(df1.values)