4

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?

No_body
  • 832
  • 6
  • 21

4 Answers4

5

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]
cs95
  • 379,657
  • 97
  • 704
  • 746
  • Thanks. I am trying to use it as a common key to join into a data-frame but it's throwing TypeError: unhashable type: 'numpy.ndarray' .Any ideas – No_body Jul 02 '19 at 16:32
  • 1
    @No_body In general, you use tuples, not lists when merging pairs: `df['final'] = df[['Latitude', 'Longitude']].agg(tuple, axis=1)`. But this is a bad idea. Bad, bad idea. You don't want to do this. You never want to do this. For the same reason that [people don't use `==` to compare floats](https://stackoverflow.com/questions/4915462/how-should-i-do-floating-point-comparison) (because of floating point inaccuracies). You asked an [XY question](https://meta.stackexchange.com/a/66378/494004). Because you did not tell us what you needed it for, none of our solutions were useful for you. – cs95 Jul 02 '19 at 16:36
4

One more using zip

df['final']=list(zip(df.Latitude,df.Longitude))
BENY
  • 317,841
  • 20
  • 164
  • 234
3

You can also use apply:

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

   Latitude              ...                                      final
0  35.827086              ...               [35.827085869, -95.67496156]
zipa
  • 27,316
  • 6
  • 40
  • 58
0

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) + ']'
Joe
  • 879
  • 2
  • 6
  • 15