[英]Replace column values based on partial string match from another dataframe python pandas
我需要根據來自不同數據幀的鍵更新一些單元格值。 鍵總是唯一的字符串,但第二個數據幀可能會或可能不會在鍵的開頭或結尾包含一些額外的文本。 (不一定用“”隔開)
Frame:
Keys Values
x1 1
x2 0
x3 0
x4 0
x5 1
Correction:
Name Values
SS x1 1
x2 AA 1
x4 1
Expected output Frame:
Keys Values
x1 1
x2 1
x3 0
x4 1
x5 1
我正在使用以下內容:
frame.loc[frame['Keys'].isin(correction['Keys']), ['Values']] = correction['Values']
問題是 isin 僅在精確的 mach 上返回 True (據我所知),這僅適用於我的數據的 30% 左右。
首先通過Frame['Keys']
加入|
extract
值對於OR
:
pat = '|'.join(x for x in Frame['Keys'])
Correction['Name'] = Correction['Name'].str.extract('('+ pat + ')', expand=False)
#remove non matched rows filled by NaNs
Correction = Correction.dropna(subset=['Name'])
print (Correction)
Name Values
0 x1 1
1 x2 1
2 x4 1
然后通過Correction['Name']
為地圖創建字典和map
:
d = dict(zip(Correction['Name'], Correction['Values']))
Frame['Values'] = Frame['Keys'].map(d).fillna(Frame['Values']).astype(int)
print (Frame)
Keys Values
0 x1 1
1 x2 1
2 x3 0
3 x4 1
4 x5 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.