将常量列表添加到pandas列 [英] Add constant list to pandas column

查看:73
本文介绍了将常量列表添加到pandas列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个df:

df=pd.DataFrame({'a':[1,2,3],'b':[4,5,6]})

我要添加的是带有恒定列表的新列 c (例如: [7,8,9,10] ).

All I want is to add a new column, c, with a constant list (for example: [7,8,9,10]).

当我尝试时:

df['c']=[7,8,9,10]

我得到:

ValueError: Length of values does not match length of index

我也尝试过使用 loc at ix -但无法弄清楚.

I tried to play also with loc, at, ix - but couldn't figure it out.

我发现一个丑陋的解决方法是执行以下操作:

An ugly workaround I found is to do something like:

df['c'] = df['b'].apply(lambda x: [7,8,9,10])

但是必须有一种更优雅的方法.

But there must be a more elegant way to do it.

推荐答案

更简单的方法是:

df['c'] =  [[7,8,9,10]]*len(df)

结果:

   a  b              c
0  1  4  [7, 8, 9, 10]
1  2  5  [7, 8, 9, 10]
2  3  6  [7, 8, 9, 10]

更新:

为避免出现每行列表的浅表复制问题(如@YOBEN_S所述),请使用:

To avoid problem of shallow copy of lists in each row (as @YOBEN_S described), use:

df['c'] = df.apply(lambda x: [7,8,9,10], axis = 1)

现在可以通过调用来更改例如第一行的 c 列中的仅第一个元素:

Now it is possible to change for example only first element in column c of the first row by calling:

df.loc[0,'c'][0]='test'

   a  b                 c
0  1  4  [test, 8, 9, 10]
1  2  5     [7, 8, 9, 10]
2  3  6     [7, 8, 9, 10]

这篇关于将常量列表添加到pandas列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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