[英]Pandas: replace column values based on match from another column
我在第一個數據框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
在dataframe1
。 ItemType
具有null
值,如yellowCabbage。 ItemType
中的ItemType
與dataframe中的ItemType
dataframe
如果相應的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。
df1.loc[df1['ItemType'].isin(df2['ItemType'])]=df2[['NewType']]
要么
df1['ItemType']=df2['ItemType'].map(df2)
提前致謝
編輯
兩個數據框中的兩個列標題具有不同的名稱。 因此,dataframe1列是ItemType1,第二個數據幀中的第一列是ItemType2。 錯過了第一次編輯。
使用map
您需要的所有邏輯:
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)
您可以將df2
轉換為由'ItemType2'
索引的系列,然后在df1
上使用replace
:
# Make df2 a Series indexed by 'ItemType'.
df2 = df2.set_index('ItemType2')['newType'].dropna()
# Replace values in df1.
df1['ItemType1'] = df1['ItemType1'].replace(df2)
或者在一行中,如果您不想更改df2
:
df1['ItemType1'] = df1['ItemType1'].replace(df2.set_index('ItemType2')['newType'].dropna())
此方法要求您將列名設置為“type”,然后可以使用merge和np.where進行設置
df3 = df1.merge(df2,how='inner',on='type')['type','newType']
df3['newType'] = np.where(df['newType'].isnull(),df['type'],df['newType'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.