简体   繁体   中英

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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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