Bill Carson
Bill Carson

Reputation: 33

How do a join two columns into another seperate column in Pandas?

Any help would be greatly appreciated. This is probably easy, but im new to Python.
I want to add two columns which are Latitude and Longitude and put it into a column called Location.

For example:

First row in Latitude will have a value of 41.864073 and the first row of Longitude will have a value of -87.706819.

I would like the 'Locations' column to display 41.864073, -87.706819.

please and thank you.

Upvotes: 3

Views: 1472

Answers (4)

TonyRyan
TonyRyan

Reputation: 328

I definitely learned something from W-B and timgeb. My idea was to just convert to strings and concatenate. I posted my answer in case you wanted the result as a string. Otherwise it looks like the answers above are the way to go.

import pandas as pd
from pandas import *  

Dic = {'Lattitude': [41.864073], 'Longitude': [-87.706819]}
DF = pd.DataFrame.from_dict(Dic)
DF['Location'] = DF['Lattitude'].astype(str) + ',' +  DF['Longitude'].astype(str)

Upvotes: 0

piRSquared
piRSquared

Reputation: 294488

Setup

df = pd.DataFrame(dict(lat=range(10, 20), lon=range(100, 110)))

zip

This should be better than using apply

df.assign(location=[*zip(df.lat, df.lon)])

   lat  lon   location
0   10  100  (10, 100)
1   11  101  (11, 101)
2   12  102  (12, 102)
3   13  103  (13, 103)
4   14  104  (14, 104)
5   15  105  (15, 105)
6   16  106  (16, 106)
7   17  107  (17, 107)
8   18  108  (18, 108)
9   19  109  (19, 109)

list variant

Though I'd still suggest tuple

df.assign(location=df[['lat', 'lon']].values.tolist())

   lat  lon   location
0   10  100  [10, 100]
1   11  101  [11, 101]
2   12  102  [12, 102]
3   13  103  [13, 103]
4   14  104  [14, 104]
5   15  105  [15, 105]
6   16  106  [16, 106]
7   17  107  [17, 107]
8   18  108  [18, 108]
9   19  109  [19, 109]

Upvotes: 2

BENY
BENY

Reputation: 323316

Data from Pir

df['New']=tuple(zip(*df[['lat','lon']].values.T))
df
Out[106]: 
   lat  lon        New
0   10  100  (10, 100)
1   11  101  (11, 101)
2   12  102  (12, 102)
3   13  103  (13, 103)
4   14  104  (14, 104)
5   15  105  (15, 105)
6   16  106  (16, 106)
7   17  107  (17, 107)
8   18  108  (18, 108)
9   19  109  (19, 109)

Upvotes: 2

timgeb
timgeb

Reputation: 78750

I question the usefulness of this column, but you can generate it by applying the tuple callable over the columns.

>>> df = pd.DataFrame([[1, 2], [3,4]], columns=['lon', 'lat'])
>>> df
>>> 
   lon  lat
0    1    2
1    3    4
>>> 
>>> df['Location'] = df.apply(tuple, axis=1)
>>> df
>>> 
   lon  lat Location
0    1    2   (1, 2)
1    3    4   (3, 4)

If there are other columns than 'lon' and 'lat' in your dataframe, use

df['Location'] = df[['lon', 'lat']].apply(tuple, axis=1)

Upvotes: 3

Related Questions