在熊猫的多个 if 条件下替换字符串



如果我有一个数据帧,如下所示:

import pandas as pd
df = pd.DataFrame({
'items': ['countryName', 'stateName', 'currencyName', 'companyName'],
'code': ['NK', 'NK', 'NK', 'NK']
})
print(df)
items code
0   countryName   NK
1     stateName   NK
2  currencyName   NK
3   companyName   NK

如何在多种条件下转换 NK,例如,如果其项目是"国家名称",将 NK 更改为朝鲜,如果其项目是"州名称",将 NK 更改为"北金斯敦"等等。请注意,这只是数据帧的一部分。谢谢。

df = pd.DataFrame({
'items': ['countryName', 'stateName', 'currencyName', 'companyName'],
'code': ['North Korea', 'North Kingstown', 'Norwegian krone', 'Northrup-King']
})
print(df)
items             code
0   countryName      North Korea
1     stateName  North Kingstown
2  currencyName  Norwegian krone
3   companyName    Northrup-King

您可以将键和值存储在 2 个不同的 dfs 中,可能存储在 excel 工作表中,并使用pd.read_excel(file)直接从那里读取它

如果我们将它们命名为dfdf1

DF:

code            items
0    NK              countryName 
1    NK              stateName 
2    NK              currencyName 
3    NK              companyName 

DF1:

code               items
0    North Korea      countryName 
1    North Kingstown  stateName 
2    Norwegian krone  currencyName 
3    Northrup-King    companyName 

然后:

df = df.merge(df1,on='items').drop('code_x', axis=1)
df.columns=['items','code']

我认为这将节省大量代码行..?

你可以在 DF 上使用 np.where。它有点脏,我相信其他人可以给你一个更干净的解决方案,但它有效。

df['code'] = np.where((df['code'] == 'NK') & (df['items'] == 'countryName'),
'North Korea',
df['code'])
df['code'] = np.where((df['code'] == 'NK') & (df['items'] == 'stateName'),
'North Kingstown',
df['code'])
... add the rest of the examples

它是如何工作的:

np.where((条件一(和(条件
  • 二(和(更多条件(...
  • 如果满足条件,则为"代码"列设置的值,例如朝鲜
  • 如果不满足条件,则保留旧值 (NK(

编辑:添加简单的动态版本

replace_dict = {'North Korea':['NK','countryName'],'North Kingstown':['NK','stateName']}
for key in replace_dict.keys():
df['code'] = np.where((df.code == replace_dict[key][0]) & (df['items'] == replace_dict[key][1]),
key,
df['code'])

我会这样做:

df = pd.DataFrame({
'items': ['countryName', 'stateName', 'currencyName', 'companyName'],
'code': ['NK', 'NK', 'NK', 'NK']
})
country_value = {'NK': "North Korea"}
state_value = {'NK': 'North Kingstown'}
currency_value = {'NK' : 'Norwegian Krone'}
company_value = {'NK': 'Northrup-king'}
def pair(x):
if x['items'] == 'countryName':
x['code'] = country_value[x['code']]
elif x['items'] == 'stateName':
x['code'] = state_value[x['code']]
elif x['items'] == 'currencyName':
x['code'] = currency_value[x['code']]
elif x['items'] == 'companyName':
x['code'] = company_value[x['code']]
return x

df.apply(pair, axis = 1)

通过这种方式,您可以添加许多国家/地区、州等键值对。

最新更新