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


i want add multiple columns pandas dataframe , set them equal existing column. there simple way of doing this? in r do:

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

in pandas results in keyerror: "['b' 'c'] not in index":

df = pd.dataframe({'a': np.arange(1,6)}) df[['b','c']] = df.a 

you can use .assign() method:

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

or little bit more creative approach:

in [41]: cols = list('bcdefg')  in [42]: df.assign(**{col:df['a'] col in cols}) out[42]:     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]:     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: @cpt_jauchefuerst mentioned in comment dataframe.assign(z=1, a=1) add columns in alphabetical order - i.e. first a added existing columns , z.


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -