【问题标题】:Apply function to two columns and map the output to a new column [duplicate]将函数应用于两列并将输出映射到新列[重复]
【发布时间】:2020-05-06 20:01:31
【问题描述】:

我是熊猫新手。想知道如何将函数应用于数据框中的两列,并将函数的输出映射到数据框中的新列。使用 pandas 语法是否完全有可能,或者我应该求助于原生 Python 来迭代数据框列中的行以生成新列?

a b

1 2
3 1
2 9

问题是如何得到,例如,新列 c 中两个数字的乘积

a b c

1 2 2
3 1 3
2 9 18

【问题讨论】:

  • 是的,你可以用 pandas 做到这一点
  • df['c'] = df['a'] * df['b']
  • @MykolaZotko 我相信乘法只是一个例子。 OP 有一个功能,并希望使用apply 应用它。

标签: python pandas numpy


【解决方案1】:

您可以使用 pandas 执行以下操作

import pandas as pd

def func(r):
    return r[0]*r[1]

df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
df['c'] = df.apply(func, axis = 1)

另外,这里是官方文档https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html

【讨论】:

  • apply + lambda 是一种不好的做法。只是说。
  • 谢谢,@harvpan,我的错,不再是 lambda
【解决方案2】:

harvpan 的评论显示了实现您的特定示例的最简单方法,但这是执行您所要求的通用方法:

def functionUsedInApply(row):
    """ The function logic for the apply function comes here. 

    row: A Pandas Series containing the a row in df.
    """
    return row['a'] * row['b']

def functionUsedInMap(value):
    """ This function is used in the map after the apply.
    For this example, if the value is larger than 5, 
    return the cube, otherwise, return the square.     

    value: a value of whatever type is returned by functionUsedInApply.
    """
    if value > 5:
        return value**3
    else:
        return value**2

df['new_column_name'] = df.apply(functionUsedInApply,axis=1).map(functionUsedInMap)

上面的函数首先将 a 列和 b 列相加,然后在 a+b 5 时返回该值的立方。

【讨论】:

    【解决方案3】:

    你可以用熊猫做。

    例如:

    def funcMul(row):
        return row['a']*row['b']
    

    那么,

    df['c'] = df.apply(funcMul,1)
    

    输出:

        a   b   c
    0   1   2   2
    1   3   1   3
    2   2   9   18
    

    【讨论】:

    • + 用于将行而不是参数传递给函数。
    猜你喜欢
    • 2020-11-15
    • 2021-11-15
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 2019-01-24
    • 1970-01-01
    相关资源
    最近更新 更多