我需要基于 pandas 數(shù)據(jù)框中的 2 列創(chuàng)建新列這是數(shù)據(jù)框的頭部 col_1 col_20 -0.5 H11 -0.5 draw2 -0.5 H33 -0.5 H14 -1.5 H25 -0.5 H17 -2.5 H48 -0.5 A29 -0.5 H112 -1.5 draw13 9.0 draw14 -0.5 draw15 -0.5 A116 -0.5 H117 -0.5 draw18 9.0 draw19 -0.5 draw20 -0.5 H121 -0.5 H222 -3.5 A1我創(chuàng)建了函數(shù):def H(d): if d['col_1'] == -0.5 & d['col_2'].isin(['H1', 'H2', 'H3', 'H4', 'H5+']): return 'W -0.5' elif d['col_1'] == -0.5 & d['col_2'].isin(['A1', 'A2', 'A3', 'A4', 'A5+', 'draw']): return 'L -0.5' elif d['col_1'] == -1.5 & d['col_2'].isin(['H2', 'H3', 'H4', 'H5+']): return 'W -1.5' elif d['col_1'] == -1.5 & d['col_2'].isin(['A1', 'A2', 'A3', 'A4', 'A5+', 'draw', 'H1']): return 'L -1.5' elif d['col_1'] == -2.5 & d['col_2'].isin(['H3', 'H4', 'H5+']): return 'W -2.5' elif d['col_1'] == -2.5 & d['col_2'].isin(['A1', 'A2', 'A3', 'A4', 'A5+', 'draw', 'H1', 'H2']): return 'L -2.5' elif d['col_1'] == -3.5 & d['col_2'].isin(['H4', 'H5+']): return 'W -3.5' elif d['col_1'] == -3.5 & d['col_2'].isin(['A1', 'A2', 'A3', 'A4', 'A5+', 'draw', 'H1', 'H2', 'H3']): return 'L -3.5' else: return 'und'然后使用 apply 創(chuàng)建新列:df['new_col'] = df.apply(H, axis=1)它返回一個(gè)錯(cuò)誤:AttributeError: ("'str' object has no attribute 'isin'", 'occurred at index 0')我需要使用 apply 或任何其他方法創(chuàng)建新列,但我更喜歡創(chuàng)建一個(gè)函數(shù)然后使用 apply
1 回答

臨摹微笑
TA貢獻(xiàn)1982條經(jīng)驗(yàn) 獲得超2個(gè)贊
df.col_2是類型string不是系列
將列表更改為集合,因?yàn)樵诖_定對象是否存在于集合中時(shí),集合要快得多。
def H(d):
if d['col_1'] == -0.5 and d['col_2'] in {'H1', 'H2', 'H3', 'H4', 'H5+'}:
return 'W -0.5'
elif d['col_1'] == -0.5 and d['col_2'] in {'A1', 'A2', 'A3', 'A4', 'A5+', 'draw'}:
return 'L -0.5'
...
添加回答
舉報(bào)
0/150
提交
取消