Adding column to pandas DataFrame containing list of other columns' values

一个人想着一个人 提交于 2021-02-04 22:17:55

问题


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

Current table:

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

Needed table:

    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).


回答1:


One way is to use 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]

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.




回答2:


you could use zip

df['new_column'] = list(zip(df.lat, df.long))


来源:https://stackoverflow.com/questions/28682095/adding-column-to-pandas-dataframe-containing-list-of-other-columns-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!