Pandas:将列值与字典键进行比较,并更新新列中的值

2024-05-21 04:14:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将dictionary“key”与pandas列进行比较,并在此基础上将dictionary“value”插入新列

示例:

sample_dict = {'0': 'a', '1': 'b', '2':'c'}

Sample_df = 

        col_1  
0         0         
1         1         
2         0         
3         1         
4         0         

如果字典的key值与col_1匹配,我想创建一个新列“col\u2”

        col_1     col_2
0         0         a
1         1         b
2         0         a
3         1         b
4         2         c

什么是最好的方法来做比较,并在新的列中有价值

现有代码:

for key in request.POST:
    df['col_2'] = pd.np.where(df.col_1.astype(str).str.contains(key), request.POST[key])

其中request.POST是查询集(字典)


Tags: samplekey示例pandasdfdictionary字典value