python - 在 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
解决方案
您可以将键和值存储在 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']
我认为这会节省很多代码行..?
推荐阅读
- java - 如何解决java中的500 Internal Server Error?
- r - 列宽不会针对某些类型的数据自动调整
- php - (Laravel)更改新星资源名称?(仅在界面上)
- python - 如何将功能传递给类?
- github - 你如何在论文中引用 GitHub 问题或 GitHub 答案
- javascript - Laravel Ajax 获取请求重定向循环
- c# - 无法在 C# Visual Studio 中使用 System.Management.Automation
- visual-studio-code - VSCode 以编程方式在扩展中搜索和替换
- mysql - MySQL 获得与每个唯一列值匹配的 n% 行
- c# - XamarinForms DataGridView (DevExpress) 不显示某些字段的值