Home > Software engineering >  Swap values of column of lists that has nans
Swap values of column of lists that has nans

Time:07-22

enter image description hereI have a data frame with columns:

pd.DataFrame({'col':[[-74.61286283, 40.56889437], [nan, nan], [-105.18943020000002, 40.07872419], [-96.83537306, 32.82099448]]})

This column is a longitude-latitude column, but I want to make it latitude-longitude. and swap their positions, so that I can use this along with another similar column to calculate distance using geopy. I tried this:

df['col'].apply(lambda x: [x[1], x[0]])

But it is giving me error: TypeError: 'float' object is not subscriptable I understand this is because of nan values, I also tried to replace nan with 0, but no luck. Then it gives error: TypeError: 'int' object is not subscriptable Please suggest.

CodePudding user response:

You can always use list comprehension to do the work since it's just switching between the values in the list.

df['new'] = [[lat,long] for long, lat in df['col']]

df
Out[15]: 
                                  col                                 new
0         [-74.61286283, 40.56889437]         [40.56889437, -74.61286283]
1                          [nan, nan]                          [nan, nan]
2  [-105.18943020000002, 40.07872419]  [40.07872419, -105.18943020000002]
3         [-96.83537306, 32.82099448]         [32.82099448, -96.83537306]

Update

Since your data has a list [0], it will cause trouble while doing the list comprehension above. If you do not want to drop it. You can do it this way to make it equal length with other rows.

df['col'].loc[df['col'].isin([[0]])] = df['col'].apply(lambda x: x   [0])

  • Related