首页 > 解决方案 > 在 Pandas 中的多个 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,例如,如果它的项目是“countryName”,则将 NK 更改为朝鲜,如果它的项目是“stateName”,则将 NK 更改为“North Kingstown”等等。请注意,这只是数据框的一部分。谢谢。

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

标签: pythonpandas

解决方案


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

如果我们命名它们df并且df1

东风:

     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']

我认为这会节省很多代码行..?


推荐阅读