如何在满足特定 if 条件的行的数据框中执行多项操作(例如,更改多列中的值)?
How do I do multiple things (e.g., change values in multiple columns) in a dataframe for rows that meet specific if conditions?
我是一名 SAS 程序员,正在尝试将我的代码翻译成 python。下面显示的 SAS 代码检查多个 if 条件,如果为真,则 do 语句允许我更改多列中的值:
if state_text eq 'ALASKA' and country_code ne 'US' then do;
flag=1;
country_code='US';
state_code='AK';
end;
pandas 数据框的等价物是什么?我无法让重新编码仅应用于满足 if 条件的行。下面的代码完成了这项工作,但看起来非常重复,如果我先列出 country_code 重新编码,那么 if 语句对于其他两个重新编码不再成立。
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
我是一名 SAS 程序员,正在尝试将我的代码翻译成 python。下面显示的 SAS 代码检查多个 if 条件,如果为真,则 do 语句允许我更改多列中的值:
if state_text eq 'ALASKA' and country_code ne 'US' then do;
flag=1;
country_code='US';
state_code='AK';
end;
pandas 数据框的等价物是什么?我无法让重新编码仅应用于满足 if 条件的行。下面的代码完成了这项工作,但看起来非常重复,如果我先列出 country_code 重新编码,那么 if 语句对于其他两个重新编码不再成立。
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