pandas -从字典向数据框添加新列 [英] pandas - add new column to dataframe from dictionary
本文介绍了 pandas -从字典向数据框添加新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想向数据框添加"D"列,如下所示:
I would like to add a column 'D' to a dataframe like this:
U,L
111,en
112,en
112,es
113,es
113,ja
113,zh
114,es
基于以下字典:
d = {112: 'en', 113: 'es', 114: 'es', 111: 'en'}
,以使结果数据框显示为:
so that the resulting dataframe appears as:
U,L,D
111,en,en
112,en,en
112,es,en
113,es,es
113,ja,es
113,zh,es
114,es,es
到目前为止,我尝试了pd.join()
方法,但无法弄清楚它如何与Dictionary一起工作.
So far I tried the pd.join()
method but I can't figured out how it works with Dictionaries.
推荐答案
Call map
and pass the dict, this will perform a lookup and return the associated value for that key:
In [248]:
d = {112: 'en', 113: 'es', 114: 'es', 111: 'en'}
df['D'] = df['U'].map(d)
df
Out[248]:
U L D
0 111 en en
1 112 en en
2 112 es en
3 113 es es
4 113 ja es
5 113 zh es
6 114 es es
这篇关于 pandas -从字典向数据框添加新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文