1

This must be trivial but I just can't find it.

For a given pandas dataframe with some indices, say idx1,idx2,idx3 I would like to add a new column efficiently using a dictionary, so something like this:

What is the best way to do it?

have = pd.DataFrame({"idx1":{"c1":1,"c2":2}, \
                     "idx2":{"c1":3,"c2":4}, \
                     "idx3":{"c1":5,"c2":6}}).transpose()
newColumn = {"idx1":"col","idx2":"to","idx3":"add"}
columnName = "myName"

#Wished output:
want = pd.DataFrame({"idx1":{"c1":1,"c2":2,"myName":"col"}, \
                  "idx2":{"c1":3,"c2":4,"myName":"to"}, \
                  "idx3":{"c1":5,"c2":6,"myName":"add"}}).transpose()
2

1 Answer 1

1
have[columnName] = pd.Series(newColumn)

Output :

>> have
    c1  c2  myName
idx1    1   2   col
idx2    3   4   to
idx3    5   6   add
Sign up to request clarification or add additional context in comments.

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.