concatenating two columns and get the new column

Viewed 91

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?

4 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]

One more using zip

df['final']=list(zip(df.Latitude,df.Longitude))

You can also use apply:

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

   Latitude              ...                                      final
0  35.827086              ...               [35.827085869, -95.67496156]

You can also combine them by typecasting each column as str then adding its values as strings together with the brackets you prefer, then finally placing them as values for the column final.

df['final'] = '[' + df['Latitude'].astype(str) + ', ' + df['Longitude'].astype(str) + ']'
Related