Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add multiple columns to DataFrame and set them equal to an existing column

Tags:

python

pandas

I want to add multiple columns to a pandas DataFrame and set them equal to an existing column. Is there a simple way of doing this? In R I would do:

df <- data.frame(a=1:5)
df[c('b','c')] <- df$a
df
  a b c
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5

In pandas this results in KeyError: "['b' 'c'] not in index":

df = pd.DataFrame({'a': np.arange(1,6)})
df[['b','c']] = df.a
like image 275
Gaurav Bansal Avatar asked Apr 14 '17 16:04

Gaurav Bansal


2 Answers

you can use .assign() method:

In [31]: df.assign(b=df['a'], c=df['a'])
Out[31]:
   a  b  c
0  1  1  1
1  2  2  2
2  3  3  3
3  4  4  4
4  5  5  5

or a little bit more creative approach:

In [41]: cols = list('bcdefg')

In [42]: df.assign(**{col:df['a'] for col in cols})
Out[42]:
   a  b  c  d  e  f  g
0  1  1  1  1  1  1  1
1  2  2  2  2  2  2  2
2  3  3  3  3  3  3  3
3  4  4  4  4  4  4  4
4  5  5  5  5  5  5  5

another solution:

In [60]: pd.DataFrame(np.repeat(df.values, len(cols)+1, axis=1), columns=['a']+cols)
Out[60]:
   a  b  c  d  e  f  g
0  1  1  1  1  1  1  1
1  2  2  2  2  2  2  2
2  3  3  3  3  3  3  3
3  4  4  4  4  4  4  4
4  5  5  5  5  5  5  5

NOTE: as @Cpt_Jauchefuerst mentioned in the comment DataFrame.assign(z=1, a=1) will add columns in alphabetical order - i.e. first a will be added to existing columns and then z.

like image 94
MaxU - stop WAR against UA Avatar answered Oct 07 '22 07:10

MaxU - stop WAR against UA


A pd.concat approach

df = pd.DataFrame(dict(a=range5))

pd.concat([df.a] * 5, axis=1, keys=list('abcde'))

   a  b  c  d  e
0  0  0  0  0  0
1  1  1  1  1  1
2  2  2  2  2  2
3  3  3  3  3  3
4  4  4  4  4  4
like image 33
piRSquared Avatar answered Oct 07 '22 06:10

piRSquared