用于 if/then/else 的 Python/pandas 习语

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17128302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:33:08  来源:igfitidea点击:

Python/pandas idiom for if/then/else

pythonpandas

提问by bjornarneson

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?

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

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?

有没有一种 Pandas-y 方法来做这样的事情?

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

采纳答案by BrenBarn

df.ix[df.type==7, ['var1001', 'var1002']] = 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:

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

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