0

I have a pandas dataframe that looks like

        some_data  another_id
id                                                            
312871     ...     abc
312977     ...     def
...

and a dictionary letters = {"abc": "x", "def": "y"}. I want to add letters as a column to my dataframe, but it is morally indexed by another_id so I can't just set df["letters"] = letters.

I'm sure there's a beautiful, elegant way to do this. What is it?

2 Answers 2

1

I hope i understand your question correct. Do you want something like:

df['letters'] = df['another_id'].map(letters)

        some_data another_id letters
id                                  
312871          5        abc       x
312977          6        def       y
Sign up to request clarification or add additional context in comments.

Comments

0

Aha!

df.merge(pd.DataFrame({"letters": letters}), left_on="dscode", right_index=True)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.