Search code examples
pythonpandasgeopy

Pandas :How to split the tuple data in column and create multiple columns


I have created a column with country name, and lattitude and longitude values in a single column. now i want the latitude value and longitude values in a different column.

code used to create the column.

df['Country_cord'] = df['Country'].apply(geolocator.geocode)

Thats how the output looks like.

0                     (España, (40.0028028, -4.003104))
1     (United Kingdom, دبي‎, الإمارات العربيّة المتّ...
2     (France métropolitaine, France, (46.603354, 1....
3     (United States of America, (39.7837304, -100.4...
4                     (Italia, (42.6384261, 12.674297))
5       (Deutschland, Europe, (51.0834196, 10.4234469))
6               (Argentina, (-34.9964963, -64.9672817))
7                    (Ireland, (52.865196, -7.9794599))
8     (België / Belgique / Belgien, (50.6407351, 4.6...
9               (מדינת ישראל, (30.8760272, 35.0015196))
10    (Schweiz/Suisse/Svizzera/Svizra, (46.7985624, ...
11          (Nederland, (52.2379891, 5.53460738161551))
12                       (Brasil, (-10.3333333, -53.2))
13                  (Portugal, (40.033265, -7.8896263))
14                  (Australia, (-24.7761086, 134.755))
15                   (Danmark, (55.670249, 10.3333283))
16      (Maroc ⵍⵎⵖⵔⵉⴱ المغرب, (31.1728192, -7.3366043))
17    (Ciudad de México, Cuauhtémoc, CDMX, 06060, Mé...
18                 (Canada, (61.0666922, -107.9917071))
19                  (Sverige, (59.6749712, 14.5208584))

i want output to be in a form where i have a column for latitude and one column for longitude.

df[lat]             df[lon]
40.0028028          46.603354
46.603354           1.8883335

Solution

  • Zipping generator expressions on numpy arrays are efficient for this:

    import pandas as pd
    
    df = pd.DataFrame([[('Country1', (341.123, 4534.123))],
                       [('Country2', (341.123, 4534.123))],
                       [('Country3', (341.123, 4534.123))],
                       [('Country4', (341.123, 4534.123))]],
                      columns=['Series1'])
    
    df['Lat'], df['Lon'] = list(zip(*((x[1][0], x[1][1]) for x in df['Series1'].values)))