【问题标题】:pandas add multiple columns with apply [duplicate]熊猫使用应用添加多列[重复]
【发布时间】:2019-09-28 14:00:52
【问题描述】:

我目前正在将经纬度坐标投影到我的 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))

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

【问题讨论】:

标签: pandas


【解决方案1】:

是的,您需要将lambda 的输出转换为pd.Series。这是一个例子:

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))

【讨论】:

  • 谢谢!这行得通。想知道将每一行转换为系列是否会使转换结果变得更慢和更好?
猜你喜欢
  • 2022-01-23
  • 2021-11-19
  • 2018-01-18
  • 2022-01-26
  • 1970-01-01
  • 2017-10-30
  • 2021-07-27
  • 2018-10-14
相关资源
最近更新 更多