Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 310
Bill Carson Avatar asked Dec 12 '25 07:12

Bill Carson


2 Answers

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)
like image 154
timgeb Avatar answered Dec 13 '25 20:12

timgeb


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]
like image 38
piRSquared Avatar answered Dec 13 '25 20:12

piRSquared