我試圖在基于字典df1的列中創建。然而,映射的列并不完全相同,字典只包含部分字串。Factordf2CodeCode
import pandas as pd
df1 = pd.DataFrame({
'Date':['2021-01-01', '2021-01-01', '2021-01-01', '2021-01-02', '2021-01-02', '2021-01-02', '2021-01-02', '2021-01-03'],
'Ratings':[9.0, 8.0, 5.0, 3.0, 2, 3, 6, 5],
'Code':['R:EST 5R', 'R:EKG EK', 'R:EKG EK', 'R:EST 5R', 'R:EKGP', 'R:EST 5R', 'R:OID_P', 'R:OID_P']})
df2 = pd.DataFrame({
'Code':['R:EST', 'R:EKG', 'R:OID'],
'Factor':[1, 1.3, 0.9]})
到目前為止,我無法正確映射資料框,因為列不完全相同。該列Code不必以“R:”開頭。
df1['Factor'] = df1['Code'].map(df2.set_index('Code')['Factor'])
這是首選輸出的樣子:
df3 = pd.DataFrame({
'Date':['2021-01-01', '2021-01-01', '2021-01-01', '2021-01-02', '2021-01-02', '2021-01-02', '2021-01-02', '2021-01-03'],
'Ratings':[9.0, 8.0, 5.0, 3.0, 2, 3, 6, 5],
'Code':['R:EST 5R', 'R:EKG EK', 'R:EKG EK', 'R:EST 5R', 'R:EKGP', 'R:EST 5R', 'R:OID_P', 'R:OID_P'],
'Factor':[1, 1.3, 1.3, 1, 1.3, 1, 0.9, 0.9]})
非常感謝!
uj5u.com熱心網友回復:
>>> df1['Code'].str[:5].map(df2.set_index('Code')['Factor'])
0 1.0
1 1.3
2 1.3
3 1.0
4 1.3
5 1.0
6 0.9
7 0.9
Name: Code, dtype: float64
>>> df2.Code.apply(lambda x:df1.Code.str.contains(x)).T.idxmax(axis=1).apply(lambda x:df2.Factor.iloc[x])
0 1.0
1 1.3
2 1.3
3 1.0
4 1.3
5 1.0
6 0.9
7 0.9
dtype: float64
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/349872.html
上一篇:使用pd.DataFrame時出現AttributeError:module'pandas'hasnoattribute'DataFrame'
