I have a pandas dataframe df
with geographical coordinates like this:
lat lon
0 48.01025772 -6.15690851
1 48.02164841 -6.10588741
2 48.03302765 -6.05480051
... ... ...
I need to convert these coordinates into a different system, and have a dedicated function for this. I plan to create two new columns, df['N']
which is paired with lat
, and df['E']
which is paired with lon
.
It's not relevant what the function looks like, so for simplicity let's call it f. The function operates like this: E, N = f(float(lat), float(lon))
Is there a way I can iterate through all rows of df
, extract the lat,lon
pair, (compute their transformation) and assign the values to the relevant columns?
You can use apply
on the df and pass axis=1
, in your function you should return a Series
and assign the 2 columns directly:
In [207]:
def foo(lat, lon):
return pd.Series([lat + 10, lon * 100])
df[['new_lat','new_lon']] = df.apply(lambda x: foo(x['lat'], x['lon']), axis=1)
df
Out[207]:
lat lon new_lat new_lon
0 48.010258 -6.156909 58.010258 -615.6909
1 48.021648 -6.105887 58.021648 -610.5887
2 48.033028 -6.054801 58.033028 -605.4801
depending on what your function is doing using apply
can and should be avoided
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With