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()
Amir Afianian
  • 2,679
  • 4
  • 22
  • 46
  • 2
    Please create a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) – Suraj Nov 02 '20 at 15:23
  • [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). Was there anything in the [User Guide](https://pandas.pydata.org/docs/user_guide/index.html) that might help? There is quite a bit there including how to make a Series or add columns to a DataFrame. – wwii Nov 02 '20 at 15:40

1 Answers1

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

Output :

>> have
    c1  c2  myName
idx1    1   2   col
idx2    3   4   to
idx3    5   6   add
Suraj
  • 2,253
  • 3
  • 17
  • 48