1

My pandas DataFrame looks like this:

            ID                      NAME  PARENT_ID
0            1                    Fruits          0
1            2                   Bananas          1
2            3                    Apples          1
3            4                   Peaches          1
4            5                     Pears          1

I would like to iterate through rows and map PARENT_ID to actual NAME values, creating a new column called PARENT_NAME, like this:

            ID                      NAME  PARENT_ID   PARENT
0            1                    Fruits          0      NaN
1            2                   Bananas          1   Fruits
2            3                    Apples          1   Fruits
3            4                   Peaches          1   Fruits
4            5                     Pears          1   Fruits

What would be the best way to achieve this?

Wolfgang
  • 67
  • 1
  • 6
  • 4
    `df['PARENT'] = df['PARENT_ID'].map(df.set_index('ID')['NAME'])` – user3483203 Sep 04 '19 at 18:08
  • @user3483203 Thank you so much! Was racking my brain over this for a day – Wolfgang Sep 04 '19 at 18:28
  • @user3483203: nice short way. Why don't you create an answer for that? – jottbe Sep 04 '19 at 18:31
  • This needs to be closed as a dupe of a question on [pandas] map column ; ythere are [1216 such questions](https://stackoverflow.com/search?q=%5Bpandas%5D+map+column+is%3Aquestion) – smci Sep 05 '19 at 01:13

1 Answers1

1

As per @user3483203 's answer:

df['PARENT'] = df['PARENT_ID'].map(df.set_index('ID')['NAME']) 
Wolfgang
  • 67
  • 1
  • 6