简体   繁体   English

Pandas:当键是数据帧的索引时,从字典向数据帧添加列

[英]Pandas: adding a column to a dataframe from dictionary, when keys are the indices of the dataframe

I know this question is similar to a lot of other questions, but I don't see an answer to this specific situation. 我知道这个问题类似于很多其他问题,但我没有看到这个具体情况的答案。 Suppose I have a dataframe with unique index values, and I want to add a column with a dictionary where the keys are the index values. 假设我有一个具有唯一索引值的数据帧,我想添加一个带有字典的列,其中键是索引值。 What is the easiest way to do this? 最简单的方法是什么?

The best way that I've come up with is the following: 我想出的最好的方法如下:

df = pd.DataFrame(index=['Aaron','Benjamin','Clinton','Daniel'])
dic = {'Aaron':25,'Benjamin':40,'Clinton':55,'Daniel':1}

df['nums']=dic
df['nums'].replace(dic)

I know that, if I want to add a column from a dictionary and the keys are another column, I can use the .map command. 我知道,如果我想从字典中添加一列并且键是另一列,我可以使用.map命令。 Is there a way to use this when the keys are the index values? 当键是索引值时,有没有办法使用它? I can't seem to make this work. 我似乎无法做到这一点。

Use a list comprehension; 使用列表理解;

df['nums'] = [dic.get(i) for i in df.index]
df

          nums
Aaron       25
Benjamin    40
Clinton     55
Daniel       1

Adding get when using map 使用map时添加get

df['num']=df.index.map(dic.get)
df
Out[1035]: 
          num
Aaron      25
Benjamin   40
Clinton    55
Daniel      1
In [28]: df['new'] = pd.Series(dic)

In [29]: df
Out[29]:
          new
Aaron      25
Benjamin   40
Clinton    55
Daniel      1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM