给定这个元组 my_tuple = ("bob", "joe", "frank")
并给定这个数据框 df
:
col_1 col_2
0 abc 2
1 cba 1
2 bca 0
有没有办法使用这个 col_2
数字作为索引并在 int
中找到它来替换 my_tuple
的值,而不需要使用 df.iterrows()
?
结果应该是:
col_1 col_2
0 abc frank
1 cba joe
2 bca bob
答案 0 :(得分:3)
您可以使用枚举将 map
与 dict
一起使用。这很快并且避免了任何 IndexErrors
(对于超出范围的索引将返回 NaN
)。
df['new_col'] = df['col_2'].map(dict(enumerate(my_tuple)))
col_1 col_2 new_col
0 abc 2 frank
1 cba 1 joe
2 bca 0 bob
答案 1 :(得分:1)
您可以像这样使用 pd.merge
:
df = (df.merge(pd.DataFrame(my_tuple), right_index=True,
left_on='col2', how='left')
.drop('col2', axis = 1).reset_index(drop = True))
您的结果将类似于:
col1 0
0 abc frank
1 cba joe
2 bca bob
然后你可以简单地重命名列:
df.columns = ['col1', 'col2']