python – Pandas:根据来自另一列的匹配替换列值

前端之家收集整理的这篇文章主要介绍了python – Pandas:根据来自另一列的匹配替换列值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在第一个数据框df1 [“ItemType”]中有一列,如下所示,

Dataframe1

  1. ItemType1
  2. redTomato
  3. whitePotato
  4. yellowPotato
  5. greenCauliflower
  6. yellowCauliflower
  7. yelloSquash
  8. redOnions
  9. YellowOnions
  10. WhiteOnions
  11. yellowCabbage
  12. GreenCabbage

我需要根据从另一个数据框创建的字典替换它.

Dataframe2

  1. ItemType2 newType
  2. whitePotato Potato
  3. yellowPotato Potato
  4. redTomato Tomato
  5. yellowCabbage
  6. GreenCabbage
  7. yellowCauliflower yellowCauliflower
  8. greenCauliflower greenCauliflower
  9. YellowOnions Onions
  10. WhiteOnions Onions
  11. yelloSquash Squash
  12. redOnions Onions

请注意,

>在dataframe2中,某些ItemType与ItemType中的相同
dataframe1.
> dataframe2中的某些ItemType具有nullCabbage等空值.
> dataframe2中的ItemType与dataframe中的ItemType无关

如果相应的Dataframe2 ItemType中的值匹配,我需要替换Dataframe1 ItemType列中的值,newType保持在bullet-points中列出的异常之上.
如果没有匹配,那么值必须是[无变化].

到目前为止,我得到了.

  1. import pandas as pd
  2.  
  3. #read second `csv-file`
  4. df2 = pd.read_csv('mappings.csv',names = ["ItemType","newType"])
  5. #conver to dict
  6. df2=df2.set_index('ItemType').T.to_dict('list')

下面给出的匹配替换不起作用.他们正在插入NaN值而不是实际值.这些是基于SO的讨论here.

  1. df1.loc[df1['ItemType'].isin(df2['ItemType'])]=df2[['NewType']]

要么

  1. df1['ItemType']=df2['ItemType'].map(df2)

提前致谢

编辑
两个数据框中的两个列标题具有不同的名称.因此,dataframe1列是ItemType1,第二个数据帧中的第一列是ItemType2.错过了第一次编辑.

解决方法

使用地图

您需要的所有逻辑:

  1. def update_type(t1,t2,dropna=False):
  2. return t1.map(t2).dropna() if dropna else t1.map(t2).fillna(t1)

让’ItemType2’成为Dataframe2的索引

  1. update_type(Dataframe1.ItemType1,Dataframe2.set_index('ItemType2').newType)
  2.  
  3. 0 Tomato
  4. 1 Potato
  5. 2 Potato
  6. 3 greenCauliflower
  7. 4 yellowCauliflower
  8. 5 Squash
  9. 6 Onions
  10. 7 Onions
  11. 8 Onions
  12. 9 yellowCabbage
  13. 10 GreenCabbage
  14. Name: ItemType1,dtype: object
  1. update_type(Dataframe1.ItemType1,Dataframe2.set_index('ItemType2').newType,dropna=True)
  2.  
  3. 0 Tomato
  4. 1 Potato
  5. 2 Potato
  6. 3 greenCauliflower
  7. 4 yellowCauliflower
  8. 5 Squash
  9. 6 Onions
  10. 7 Onions
  11. 8 Onions
  12. Name: ItemType1,dtype: object

校验

  1. updated = update_type(Dataframe1.ItemType1,Dataframe2.set_index('ItemType2').newType)
  2.  
  3. pd.concat([Dataframe1,updated],axis=1,keys=['old','new'])

定时

  1. def root(Dataframe1,Dataframe2):
  2. return Dataframe1['ItemType1'].replace(Dataframe2.set_index('ItemType2')['newType'].dropna())
  3.  
  4. def piRSquared(Dataframe1,Dataframe2):
  5. t1 = Dataframe1.ItemType1
  6. t2 = Dataframe2.set_index('ItemType2').newType
  7. return update_type(t1,t2)

猜你在找的Python相关文章