我有一个简单的数据帧(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
用途:
相关问题 更多 >
编程相关推荐