在根据条件更改数据框列时,我习惯了以下操作(在这种情况下,每个女人的工资都是 200)。
import pandas as pd
df = pd.DataFrame([[False,100],[True,100],[True,100]],columns=['female','wage'])
df.loc[df['female'] == True,'wage'] = 200
PEP 8 样式约定检查器(在 Spyder 中)在第 3 行中建议:
comparison to True should be 'if cond is True:' or 'if cond:'
将最后一行更改为
df.loc[df['female'] is True,'wage'] = 200
产量
KeyError: 'cannot use a single bool to index into setitem'
因为现在语句被评估为单个 bool 值而不是系列。
这是一种必须偏离样式约定的情况吗?
最佳答案
您应该在不进行比较的情况下使用 df['female']
,而不是使用任何运算符与 True
进行比较。 df['female']
已经是您需要的面具了。
使用 ==
与 True
进行比较几乎总是一个坏主意,即使在 NumPy 或 Pandas 中也是如此。
关于python - 与 pandas 中的 bool 值进行比较时,我是否必须偏离 PEP 8 样式约定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51314108/