給定 DataFramedf和字典test_dict:
import pandas as pd
# initialize data of lists.
data = {'ref':['Gfg', 'Gfg', 'Gfg', 'Gfg', 'isR', 'Qst', 'jPu'],
'position':[1, 3, 1, 1, 2, 1, np.nan]}
# Create DataFrame
df = pd.DataFrame(data)
ref position
0 Gfg 1.0
1 Gfg 3.0
2 Gfg 1.0
3 Gfg 1.0
4 isR 2.0
5 Qst 1.0
6 jPu NaN
test_dict = {"Gfg" : [5, 3, 6], "isR" : [8, 4], "Qst" : [10, 11]}
我正在嘗試通過將專案與字典鍵df匹配來創建一個新列df.ref,然后根據中的值從配對串列中回傳test_dict值df.position
這將產生以下結果:
ref position new_col
0 Gfg 1.0 5
1 Gfg 3.0 6
2 Gfg 1.0 5
3 Gfg 1.0 5
4 isR 2.0 4
5 Qst 1.0 10
6 jPu NaN NaN
uj5u.com熱心網友回復:
這是一種方法:
map test_dict到“ref”列并使用串列推導遍歷每行中的串列并使用“位置”對它們進行索引:
df['new_col'] = [lst if isinstance(lst, float) else lst[int(i)-1] for i, lst in zip(df['position'], df['ref'].map(test_dict))]
輸出:
ref position new_col
0 Gfg 1.0 5.0
1 Gfg 3.0 6.0
2 Gfg 1.0 5.0
3 Gfg 1.0 5.0
4 isR 2.0 4.0
5 Qst 1.0 10.0
6 jPu NaN NaN
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432092.html
