Python pandas - 从字典向数据框添加新列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29794959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:01:40  来源:igfitidea点击:

pandas - add new column to dataframe from dictionary

pythonpandas

提问by Fabio Lamanna

I would like to add a column 'D' to a dataframe like this:

我想在这样的数据框中添加一列“D”:

U,L
111,en
112,en
112,es
113,es
113,ja
113,zh
114,es

based on the following Dictionary:

基于以下字典:

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

So far I tried the pd.join()method but I can't figured out how it works with Dictionaries.

到目前为止,我尝试了该pd.join()方法,但我无法弄清楚它如何与 Dictionaries 一起使用。

采纳答案by EdChum

Call mapand pass the dict, this will perform a lookup and return the associated value for that key:

调用map并传递 dict,这将执行查找并返回该键的关联值:

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

回答by Yuan Tao

I got TypeError: 'dict' object is not callableerror for EdChum's solution when I try to use index.map()... And I haven't found a way to get index as Series.

TypeError: 'dict' object is not callable当我尝试使用 index.map() 时,我遇到了 EdChum 解决方案的错误......而且我还没有找到将索引作为系列获取的方法。

So I found another solution to this problem by creating a Series object from the dict object first.

所以我找到了另一个解决这个问题的方法,首先从 dict 对象创建一个 Series 对象。

new_d = pd.Series(d)

And then do the pd.join with the column you like. That may help.

然后对您喜欢的列执行 pd.join。这可能会有所帮助。

回答by Sawant

Here is a simpler way that should work well too:

这是一种更简单的方法,应该也能很好地工作:

df["D"] = pd.Series(d)

df["D"] = pd.Series(d)

Note: The dict keys need to be in the DataFrame index for this.

注意:为此,dict 键需要位于 DataFrame 索引中。