与 pandas 中的布尔值进行比较时,我是否必须偏离PEP 8样式约定? [英] Do I have to deviate from PEP 8 style conventions when comparing to booleans in pandas?

查看:109
本文介绍了与 pandas 中的布尔值进行比较时,我是否必须偏离PEP 8样式约定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据条件更改数据框列时,我习惯于以下情况(在这种情况下,每个女性的工资为200).

I used to the following when altering a dataframe column based on a condition (in this case, every woman gets a wage of 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行中进行提示:

The PEP 8 Style convention checker (in Spyder) recommends in line 3:

与True的比较应为如果cond为True:"或如果cond:"

comparison to True should be 'if cond is True:' or 'if cond:'

将最后一行更改为

df.loc[df['female'] is True,'wage'] = 200

收益

KeyError:不能使用单个布尔值索引到setitem中"

KeyError: 'cannot use a single bool to index into setitem'

因为现在该语句被评估为单个布尔值,而不是序列.

because now the statement is evaluated to a single boolean value and not to a Series.

这是否是一种必须偏离样式约定的情况?

Is this a case where one has to deviate from styling conventions?

推荐答案

您应该使用df['female']而不进行比较,而不是使用任何运算符将其与True进行比较. df['female']已经是您需要的蒙版.

You should use df['female'] with no comparison, rather than comparing to True with any operator. df['female'] is already the mask you need.

True==进行比较几乎总是一个坏主意,即使在NumPy或Pandas中也是如此.

Comparison to True with == is almost always a bad idea, even in NumPy or Pandas.

这篇关于与 pandas 中的布尔值进行比较时,我是否必须偏离PEP 8样式约定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆