0

I'm trying to set multiple new columns to one column and, separately, multiple new columns to multiple scalar values. Can't do either. Any way to do it other than setting each one individually?

df=pd.DataFrame(columns=['A','B'],data=np.arange(6).reshape(3,2))
df.loc[:,['C','D']]=df['A']
df.loc[:,['C','D']]=[0,1]
Lamakaha
  • 869
  • 1
  • 9
  • 17

3 Answers3

1
for c in ['C', 'D']:
    df[c] = d['A']

df['C'] = 0
df['D'] = 1
zyxue
  • 7,904
  • 5
  • 48
  • 74
  • thanks for the response but I was explicitly asking if there a way to achieve this without assigning one to one directly ( i get the loop but still wanted to see something in the pandas library giving me that assignment). Especially assigning scalars one by one. Imagine if I have a good chunk of those – Lamakaha Aug 31 '15 at 23:03
  • I am not aware of any, but why against a for loop? It's simple and clean. – zyxue Aug 31 '15 at 23:05
0

Maybe it is what you are looking for.

df=pd.DataFrame(columns=['A','B'],data=np.arange(6).reshape(3,2))

df['C'], df['D'] = df['A'], df['A']
df['E'], df['F'] = 0, 1

# Result
   A  B  C  D  E  F
0  0  1  0  0  0  1
1  2  3  2  2  0  1
2  4  5  4  4  0  1
Romain
  • 19,910
  • 6
  • 56
  • 65
0

The assign method will create multiple, new columns in one step. You can pass a dict() with the column and values to return a new DataFrame with the new columns appended to the end.

Using your examples:

df = df.assign(**{'C': df['A'], 'D': df['A']})

and

df = df.assign(**{'C': 0, 'D':1})

See this answer for additional detail: https://stackoverflow.com/a/46587717/4843561

xfsrg
  • 1