我正在尋找以下資料幀之間差異的摘要,但部分匹配計數為非差異。區分部分匹配和完全匹配的分隔符是:或-(或兩者的組合)。
部分匹配的示例是Football-001and Football-001:NFL-Lombardi。或者,Football-002不會被視為部分匹配Football-001:NFL-Lombardi
import pandas as pd
import numpy as np
abc = {'Sport' : ['Football-001', 'Basketball-001', 'Baseball-002', 'Hockey-002'], 'Year' : ['2021','2021','2022','2022'], 'ID' : ['1','2','3','4']}
abc = pd.DataFrame({k: pd.Series(v) for k, v in abc.items()})
abc
xyz = {'SportLeague' : ['Football-001:NFL-Lombardi', 'Basketball-001-NBA-OBrien', 'Baseball-002:MLB:Commissioner', 'Hockey-002-NHL:Stanley', 'Soccer:MLS-Phillip:Anschutz'], 'Year' : ['2022','2022','2022','2022', '2022'], 'ID' : ['2','3','2','4', '1']}
xyz = pd.DataFrame({k: pd.Series(v) for k, v in xyz.items()})
xyz = xyz.sort_values(by = ['ID'], ascending = True)
print(abc, xyz)
已經嘗試過的代碼如下。這將適用于一個分隔符,但不適用于多個(注意:下面似乎只適用于一個分隔符,我正在尋找一個適用于或:的解決方案建議)::-
xyz = xyz.assign(**xyz['SportLeague'].str.split(':', expand=True).set_axis(['Sport','League'], axis=1))
xyz_c = xyz.reindex(abc.columns, axis=1)
xyz_c.compare(abc.reindex_like(xyz_c), keep_shape=True, keep_equal=True)
series.str.split(re.compile("[:-]"))
Example of data before comparison:
[![enter image description here][1]][1]
Example of summary df:
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/fAcDf.png
[2]: https://i.stack.imgur.com/TzWy9.png
uj5u.com熱心網友回復:
根據評論,試試這個:
import pandas as pd
import numpy as np
abc = {'Sport' : ['Football-001', 'Basketball-001', 'Baseball-002', 'Hockey-002'], 'Year' : ['2021','2021','2022','2022'], 'ID' : ['1','2','3','4']}
abc = pd.DataFrame({k: pd.Series(v) for k, v in abc.items()})
abc
xyz = {'SportLeague' : ['Football-001:NFL-Lombardi', 'Basketball-001-NBA-OBrien', 'Baseball-002:MLB:Commissioner', 'Hockey-002-NHL:Stanley', 'Soccer:MLS-Phillip:Anschutz'], 'Year' : ['2022','2022','2022','2022', '2022'], 'ID' : ['2','3','2','4', '1']}
xyz = pd.DataFrame({k: pd.Series(v) for k, v in xyz.items()})
xyz = xyz.sort_values(by = ['ID'], ascending = True)
tm = '(' '|'.join([f'{x}' for x in abc['Sport']]) ')'
temp = xyz['SportLeague'].str.extract(tm)
merged = temp.merge(abc, left_on=0, right_on='Sport').drop(0, axis=1)
not_merged = xyz[temp[0].isna()]
not_merged = not_merged.rename({x:y for (x,y) in zip(not_merged.columns, merged.columns)}, axis=1)
merged['Changes'] = 1
not_merged['Changes'] = 0
pd.concat([merged, not_merged])
輸出:
Sport Year ID Changes
0 Football-001 2021 1 1
1 Baseball-002 2022 3 1
2 Basketball-001 2021 2 1
3 Hockey-002 2022 4 1
4 Soccer:MLS-Phillip:Anschutz 2022 1 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/482325.html
上一篇:如何合并或更新資料框?
