Skip to content Skip to sidebar Skip to footer

Creating Columns Dynamically. Assigning Them A Constant Row Vector

Say I have some dataframe df. I would like to add to it four columns ['A', 'B', 'C, 'D'] that do not exist yet, and that will hold a constant row vector [1, 2, 3, 4]. When I try to

Solution 1:

I think this is the way to go. Pretty clear logic here.

In[19]: pd.concat([df,DataFrame([[1,2,3,4]],columns=list('ABCD'),index=df.index)],axis=1)
Out[19]: 
  labelsomedataABCD0b1.46210812341c-2.06014112342e-0.32241712343f-0.38405412344c1.13376912345e-1.09989112346d-0.17242812347e-0.87785812348c0.04221412349e0.5828151234

Multi-assignment could work, but I don't think its a great soln because its so error prone (e.g. say some of your columns already exists, what should you do?). And the rhs is very problematic as you normally want to align, so its not obvious that you need to broadcast.

Solution 2:

You can do it column by column:

import pandas as pd
df = pd.DataFrame(index=range(5))
cols = ['A', 'B', 'C', 'D', 'E']
vals = [1, 2, 3, 4, 5]
for c, v inzip(cols, vals):
    df[c] = v
print df

Note that the last method mentioned in the other question you referred works similarly by creating each column before hand:

for a in attrlist:
    df[a] = 0

Post a Comment for "Creating Columns Dynamically. Assigning Them A Constant Row Vector"