Python/Pandas习惯用语if/then/else [英] Python/pandas idiom for if/then/else

查看:128
本文介绍了Python/Pandas习惯用语if/then/else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在整个熊猫数据帧上执行计算后,我需要返回并根据另一个变量的值覆盖变量计算(通常设置为零).有没有更简洁/惯用的方式来执行这种操作?

After performing calculations on an entire pandas dataframe, I need to go back and override variable calculations (often setting to zero) based on the value of another variable(s). Is there a more succinct/idiomatic way to perform this kind of operation?

df['var1000'][df['type']==7] = 0
df['var1001'][df['type']==7] = 0
df['var1002'][df['type']==7] = 0
...
df['var1099'][df['type']==7] = 0

是否有一种类似熊猫的方式?

Is there a pandas-y way to do something like this?

if (df['type']==7):
    df['var1000'] = 0
    df['var1001'] = 0
    df['var1002'] = 0
    ...
    df['var1099'] = 0

推荐答案

df.ix[df.type==7, ['var1001', 'var1002']] = 0

如果要在所有列上执行此操作,则只需执行df.ix[df.type==7] = 0.或者,当然,如果您有要替换其值的列的列表,则可以在第二个插槽中传递该列表:

If you're doing it on all columns, you can just do df.ix[df.type==7] = 0. Or of course if you have a list of the columns whose values you want to replace, you can pass that list in the second slot:

columnsToReplace = ['var1001', 'var1002', ...]
df.ix[df.type==8, columnsToReplace] = 0

这篇关于Python/Pandas习惯用语if/then/else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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