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).
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.
you could use zip
df['new_column'] = list(zip(df.lat, df.long))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With