Pandas 使用“应用”添加多个列

Pandas 使用“应用”添加多个列,pandas,Pandas,我目前正在将经纬度坐标投影到pandas数据框中的笛卡尔平面。因此,我有一种投影方法,如下所示: def convert_lat_long_xy(lat, lo): return x, y 这将返回一个元组,我可以在我的数据帧上使用这个方法,如下所示: df.apply(lambda x: convert_lat_long_xy(x.latitude, x.longitude), axis=1)) 现在,我想做的是在我的数据框中创建两个额外的列,称为“x”和“y”,以保存这些值。我知

我目前正在将经纬度坐标投影到pandas数据框中的笛卡尔平面。因此,我有一种投影方法,如下所示:

def convert_lat_long_xy(lat, lo):
    return x, y
这将返回一个元组,我可以在我的数据帧上使用这个方法,如下所示:

df.apply(lambda x: convert_lat_long_xy(x.latitude, x.longitude), axis=1))
现在,我想做的是在我的数据框中创建两个额外的列,称为“x”和“y”,以保存这些值。我知道我可以做一些事情,比如:

df['proj'] = df.apply(lambda x: convert_lat_long_xy(x.latitude, x.longitude), axis=1))

但是是否可以将值添加到两个不同的列中?

是的,您需要将lambda的输出转换为。下面是一个例子:

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
对于您的特定情况,df.apply将如下所示:

df[['x', 'y']] = df.apply(lambda x: pd.Series(convert_lat_long_xy(x.latitude, x.longitude)), axis=1))

非常感谢。这很有效。想知道转换为每行的序列是否会使转换结果变得缓慢和更好?