将函数应用于 pandas 数据框的两列以获取两个新列

Applying a function to two columns of pandas dataframe to get two new columns

我有一个包含 LongitudeLatitude 列的 pandas 数据框。我想从他们那里得到 XYutm 中有一个名为 from_latlon 的函数可以执行此操作。它接收 LatitudeLongitude 并给出 [X,Y]。这是我的做法:

    def get_X(row):
        return utm.from_latlon(row['Latitude'], row['Longitude'])[0]

    def get_Y(row):
        return utm.from_latlon(row['Latitude'], row['Longitude'])[1] 

    df['X'] = df.apply(get_X, axis=1)
    df['Y'] = df.apply(get_Y, axis=1)

我想定义一个函数 get_XY 并应用 from_latlon 一次以节省时间。我看了一下 here, here and here 但我找不到一种方法来用一个 apply 函数制作两列。谢谢。

您可以 return 您的函数中的列表:

d = pandas.DataFrame({
    "A": [1, 2, 3, 4, 5],
    "B": [8, 88, 0, -8, -88]
})

def foo(row):
    return [row["A"]+row["B"], row["A"]-row["B"]]

>>> d.apply(foo, axis=1)
    A   B
0   9  -7
1  90 -86
2   3   3
3  -4  12
4 -83  93

您还可以return一个系列。这使您可以指定 return 值的列名称:

def foo(row):
    return pandas.Series({"X": row["A"]+row["B"], "Y": row["A"]-row["B"]})

>>> d.apply(foo, axis=1)
    X   Y
0   9  -7
1  90 -86
2   3   3
3  -4  12
4 -83  93

我合并了来自类似线程的几个答案,现在有一个通用的多列输入、多列输出模板,我在 Jupyter/pandas:

# plain old function doesn't know about rows/columns, it just does its job.
def my_func(arg1,arg2):
    return arg1+arg2, arg1-arg2  # return multiple responses

df['sum'],df['difference'] = zip(*df.apply(lambda x: my_func(x['first'],x['second']),axis=1))