Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenating two columns and get the new column

I have 2 col as

  Latitude       Longitude    
  35.827085869   -95.67496156

Both are in float and I want it to convert into

 Latitude       Longitude       final
 35.827085869   -95.67496156    [35.827085869,-95.67496156]

How can I achieve that?

like image 619
No_body Avatar asked Dec 13 '22 11:12

No_body


2 Answers

Convert the two columns to a list of lists, then assign it to a new column.

# Pandas < 0.24
# df['final'] = df[['Latitude', 'Longitude']].values.tolist()
# Pandas >= 0.24
df['final'] = df[['Latitude', 'Longitude']].to_numpy().tolist()
df

    Latitude  Longitude                         final
0  35.827086 -95.674962  [35.827085869, -95.67496156]

Note that they have to be lists, you cannot assign them back as a single column if you're assigning a NumPy array.


Another choice is to use agg for reductions:

df['final'] = df[['Latitude', 'Longitude']].agg(list, axis=1)
df

    Latitude  Longitude                         final
0  35.827086 -95.674962  [35.827085869, -95.67496156]
like image 83
cs95 Avatar answered Dec 16 '22 00:12

cs95


One more using zip

df['final']=list(zip(df.Latitude,df.Longitude))
like image 23
BENY Avatar answered Dec 16 '22 00:12

BENY