I am currently projecting the latitude, longitude coordinates to a cartesian plane in my pandas data frame. So, I have a method for projection as:
def convert_lat_long_xy(lat, lo):
return x, y
So this returns a tuple and I can use this method on my dataframe as:
df.apply(lambda x: convert_lat_long_xy(x.latitude, x.longitude), axis=1))
Now, what I would like to do is create two extra columns in my data frame called 'x' and 'y' to hold these values. I know I can do something like:
df['proj'] = df.apply(lambda x: convert_lat_long_xy(x.latitude, x.longitude), axis=1))
But is it possible to add the values to two different columns?
Yes, you need to convert the output of lambda
into pd.Series. Here's an example:
In [1]: import pandas as pd
In [2]: pd.DataFrame(["1,2", "2,3"], columns=["coord"])
Out[2]:
coord
0 1,2
1 2,3
In [3]: df = pd.DataFrame(["1,2", "2,3"], columns=["coord"])
In [4]: df.apply(lambda x: pd.Series(x["coord"].split(",")), axis=1)
Out[4]:
0 1
0 1 2
1 2 3
In [5]: df[["x", "y"]] = df.apply(lambda x: pd.Series(x["coord"].split(",")), axis=1)
In [6]: df
Out[6]:
coord x y
0 1,2 1 2
1 2,3 2 3
For your particular case, df.apply
will become like this:
df[['x', 'y']] = df.apply(lambda x: pd.Series(convert_lat_long_xy(x.latitude, x.longitude)), axis=1))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments