将多个列添加到DataFrame并将其设置为等于现有列 [英] Add multiple columns to DataFrame and set them equal to an existing column

查看:120
本文介绍了将多个列添加到DataFrame并将其设置为等于现有列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将多个列添加到pandas DataFrame,并将它们设置为等于现有列.有没有简单的方法可以做到这一点?在R中,我会这样做:

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

pandas中将导致在KeyError: "['b' 'c'] not in index"中:

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

推荐答案

,您可以使用或更富创意的方法:

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

另一种解决方案:

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

注意:正如注释DataFrame.assign(z=1, a=1)中提到的@Cpt_Jauchefuerst,将按字母顺序添加列-即,首先将a添加到现有列,然后添加z.

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.

这篇关于将多个列添加到DataFrame并将其设置为等于现有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆