【发布时间】:2016-11-22 19:54:46
【问题描述】:
我在第一个数据框df1["ItemType"] 中有一个列,如下所示,
数据框1
ItemType1
redTomato
whitePotato
yellowPotato
greenCauliflower
yellowCauliflower
yelloSquash
redOnions
YellowOnions
WhiteOnions
yellowCabbage
GreenCabbage
我需要根据从另一个数据框创建的字典来替换它。
Dataframe2
ItemType2 newType
whitePotato Potato
yellowPotato Potato
redTomato Tomato
yellowCabbage
GreenCabbage
yellowCauliflower yellowCauliflower
greenCauliflower greenCauliflower
YellowOnions Onions
WhiteOnions Onions
yelloSquash Squash
redOnions Onions
请注意,
- 在
dataframe2中的一些ItemType与ItemType相同dataframe1。 - dataframe2 中的一些
ItemType具有null值,例如 YellowCabbage。 -
数据帧2 中的
ItemType相对于dataframe中的ItemType出现故障
如果对应的Dataframe2 ItemType 中的值与newType 匹配,我需要替换Dataframe1 ItemType 列中的值,并牢记要点中列出的上述例外情况。
如果没有匹配,则值需要保持原样[没有变化]。
到目前为止我得到的是。
import pandas as pd
#read second `csv-file`
df2 = pd.read_csv('mappings.csv',names = ["ItemType", "newType"])
#conver to dict
df2=df2.set_index('ItemType').T.to_dict('list')
下面给出的匹配替换不起作用。他们正在插入 NaN 值而不是实际值。这些基于对 SO 的讨论 here。
df1.loc[df1['ItemType'].isin(df2['ItemType'])]=df2[['NewType']]
或
df1['ItemType']=df2['ItemType'].map(df2)
提前致谢
编辑
两个数据框中的两个列标题具有不同的名称。所以dataframe1上的列是ItemType1,第二个数据框中的第一列是ItemType2。第一次编辑时错过了。
【问题讨论】:
标签: python python-2.7 pandas dataframe