Eric Miller
Eric Miller

Reputation: 1407

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

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

Upvotes: 16

Views: 13269

Answers (2)

Alex Riley
Alex Riley

Reputation: 177078

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.

Upvotes: 25

Haleemur Ali
Haleemur Ali

Reputation: 28313

you could use zip

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

Upvotes: 2

Related Questions