将列添加到包含其他列值列表的pandas DataFrame中 [英] Adding column to pandas DataFrame containing list of other columns' values

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

问题描述

我有一个DataFrame,我需要向其中添加一列.该列必须是两个值的列表:

I have a DataFrame to which I need to add a column. The column needs to be a list of two values:

当前表:

    lat  long  other_value
0   50   50    x
1   60   50    y
2   70   50    z
3   80   50    a

所需表:

    lat  long  other_value  new_column
0   50   50    x            [50, 50]
1   60   50    y            [60, 50]
2   70   50    z            [70, 50]
3   80   50    a            [80, 50]

我知道这非常简单,但是文档似乎并没有涵盖(至少显然没有).

I know this is super simple, but the documentation doesn't seem to cover this (at least not apparently).

推荐答案

一种方法是使用 tolist():

>>> df['new_column'] = df[['lat', 'long']].values.tolist()
>>> df
   lat  long other_value new_column
0   50    50           x   [50, 50]
1   60    50           y   [60, 50]
2   70    50           z   [70, 50]
3   80    50           a   [80, 50]

不过,总的来说,我会非常警惕在DataFrames中使用列表,因为它们在列中更难操作,并且您不会从整数/浮点数中获得很多性能上的好处.

In general though, I'd be very wary of using lists in DataFrames since they're more difficult to manipulate in columns and you don't get many of the performance benefits that come with integers/floats.

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

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