python – Pandas:根据来自另一列的匹配替换列值
|
我在第一个数据框df1 [“ItemType”]中有一列,如下所示, Dataframe1 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中的相同 如果相应的Dataframe2 ItemType中的值匹配,我需要替换Dataframe1 ItemType列中的值,newType保持在bullet-points中列出的异常之上. 到目前为止,我得到了. 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) 提前致谢 编辑 解决方法使用地图您需要的所有逻辑: def update_type(t1,t2,dropna=False):
return t1.map(t2).dropna() if dropna else t1.map(t2).fillna(t1)
让’ItemType2’成为Dataframe2的索引 update_type(Dataframe1.ItemType1,Dataframe2.set_index('ItemType2').newType)
0 Tomato
1 Potato
2 Potato
3 greenCauliflower
4 yellowCauliflower
5 Squash
6 Onions
7 Onions
8 Onions
9 yellowCabbage
10 GreenCabbage
Name: ItemType1,dtype: object
update_type(Dataframe1.ItemType1,Dataframe2.set_index('ItemType2').newType,dropna=True)
0 Tomato
1 Potato
2 Potato
3 greenCauliflower
4 yellowCauliflower
5 Squash
6 Onions
7 Onions
8 Onions
Name: ItemType1,dtype: object
校验 updated = update_type(Dataframe1.ItemType1,Dataframe2.set_index('ItemType2').newType)
pd.concat([Dataframe1,updated],axis=1,keys=['old','new'])
定时 def root(Dataframe1,Dataframe2):
return Dataframe1['ItemType1'].replace(Dataframe2.set_index('ItemType2')['newType'].dropna())
def piRSquared(Dataframe1,Dataframe2):
t1 = Dataframe1.ItemType1
t2 = Dataframe2.set_index('ItemType2').newType
return update_type(t1,t2)
(编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- python – 在NumPy中将元素方式和矩阵乘法与多维
- python 把文件中的每一行以数组的元素放入数组中
- Python基于列表list实现的CRUD操作功能示例
- 【Python有坑系列】报错NameError: name reload
- python – 使用ZMQ PUB与.connect()或.bind()方法
- python – Selenium’WebElement’对象没有属性’
- #《Hadoop权威指南》——Hadoop简介
- 在matplotlib.image.AxesImage对象上的python pl
- 我无法使用python中的遗传算法得到正确的答案
- python 采集中文乱码问题的完美解决方法
