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

时间:2018-03-25 19:26:46

标签: python python-3.x pandas

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. Is there a way to use this when the keys are the index values? I can't seem to make this work.

3 个答案:

答案 0 :(得分:3)

Use a list comprehension;

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

          nums
Aaron       25
Benjamin    40
Clinton     55
Daniel       1

答案 1 :(得分:2)

Adding get when using map

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

答案 2 :(得分:2)

In [28]: df['new'] = pd.Series(dic)

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