使用不同的dataframe替换datafram中文本的值

2024-04-23 12:08:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的数据帧(df1),在这里我用replace函数替换值(见下文)。我不必总是在代码中更改要替换的项的名称,而是希望在excel工作表中执行此操作,其中的列或行给出了应替换的不同名称。我将excel作为数据框(df2)导入。我所缺少的是将df2中的信息转换为replace函数的scrip。你知道吗

df1 = pd.DataFrame({'Product':['Tart', 'Cookie', 'Black'],
                   'Quantity': [1234, 4, 333]})

print(df1)
  Product  Quantity
0      Tart      1234
1      Cookie    4
2      Black     333

这就是我目前所用的

sales = sales.replace (["Tart","Tart2", "Cookie", "Cookie2"], "Tartlet")
sales = sales.replace (["Ham and cheese Sandwich" , "Chicken focaccia"], "Sandwich")

更换后

print(df1)
  Product  Quantity
0      Tartlet   1234
1      Tartlet    4
2      Black     333

这就是我的dataframe2从excel文件导入后的样子(我可以灵活地设计它)

df2 = pd.read_excel (setup_folder / "Product Replacements.xlsx", index_col= 0)

print (df2)
      Tartlet  Sandwich
0      Tart      Ham and cheese Sandwich
1      Tart2    Chicken Focaccia
2      Cookie2     nan

Tags: 数据函数cookieproductexcelreplacequantityblack
1条回答
网友
1楼 · 发布于 2024-04-23 12:08:12

用途:

df2 = pd.DataFrame({'Tartlet':['Tart', 'Tart2', 'Cookie'],
                    'Sandwich': ['Ham and Cheese Sandwich', 'Chicken Focaccia', 'another']})

#swap key values in dict
#http://stackoverflow.com/a/31674731/2901002
d1 = {k: oldk for oldk, oldv in df2.items() for k in oldv}
print (d1)
{'Tart': 'Tartlet', 'Tart2': 'Tartlet', 'Cookie': 'Tartlet', 'Ham and Cheese Sandwich': 
 'Sandwich', 'Chicken Focaccia': 'Sandwich', 'another': 'Sandwich'}

df1['Product'] = df1['Product'].replace(d1)
#for improve performance
#df1['Product'] = df1['Product'].map(d1).fillna(df1['Product'])
print (df1)
   Product  Quantity
0  Tartlet      1234
1  Tartlet         4
2    Black       333

相关问题 更多 >