Python 对于满足特定if条件的行,如何在数据帧中执行多项操作(例如,更改多列中的值)?
我是一名SAS程序员,试图将我的代码翻译成python。下面显示的SAS代码检查多个if条件,如果为true,则do语句允许我更改多列中的值:Python 对于满足特定if条件的行,如何在数据帧中执行多项操作(例如,更改多列中的值)?,python,pandas,dataframe,apply,Python,Pandas,Dataframe,Apply,我是一名SAS程序员,试图将我的代码翻译成python。下面显示的SAS代码检查多个if条件,如果为true,则do语句允许我更改多列中的值: if state_text eq 'ALASKA' and country_code ne 'US' then do; flag=1; country_code='US'; state_code='AK'; end; 熊猫数据帧的等价物是什么?我无法使重新编码仅应用于满足if条件的行。下面的代码完成了这项工作,但看起来非常重复,
if state_text eq 'ALASKA' and country_code ne 'US' then do;
flag=1;
country_code='US';
state_code='AK';
end;
熊猫数据帧的等价物是什么?我无法使重新编码仅应用于满足if条件的行。下面的代码完成了这项工作,但看起来非常重复,如果我首先列出国家代码recode,那么if语句对于其他两个recode就不再正确
df.loc[((df['state_text'] == 'ALASKA') & (df['country_code'] != 'US')), 'flag'] = '1'
df.loc[((df['state_text'] == 'ALASKA') & (df['country_code'] != 'US')), 'state_code'] = 'AK'
df.loc[((df['state_text'] == 'ALASKA') & (df['country_code'] != 'US')), 'country_code'] = 'US
您可以将列名传递到
loc
:
df.loc[((df['state_text'] == 'ALASKA') & (df['country_code'] != 'US')),
['flag', 'state_text', 'country_code']
] = ['1', 'AK', 'US']
样本数据:
state_text country_code flag
0 ALASKA CA 0
1 OH US 0
代码后的输出:
state_text country_code flag
0 AK US 1
1 OH US 0
这很聪明。唯一的问题是我得到了一个索引中没有的['flag']的KeyError。数据帧中不存在此字段。我需要先初始化它吗?如果是,我该怎么做?有趣的是,当我单独运行带有flag的行时,我没有得到这个错误。@SAS2PYTHON它在我的系统上工作,即使
flag
不存在。你可能有更老版本的熊猫。在这种情况下,是的,只需在该行前面加上df['flag']='0'。太好了!非常感谢。