【问题标题】:Using pandas apply with if condition使用熊猫适用于 if 条件
【发布时间】:2021-05-29 22:33:49
【问题描述】:

下面我试图举例说明我的问题。我不确定我是否理解正确收到的以下错误。 f['C'], df['D'] = zip(*df.apply(lambda x: 0 if x['A'] == 1 else some_func(x['A'], x['B']), axis=1)) TypeError: 'int' object is not iterable

是不是因为在这种情况下,当 x['A'] == 1 时返回的 0 只是单个 int 并且因此不能解压缩?当然,任何解决此错误的帮助将不胜感激! 干杯。

import pandas as pd

# A function that returns multiple things.
def some_func(x,y):
    return x+y, x-y

# Example DataFrame
df = pd.DataFrame({'A': range(5), 'B':range(5,10,1)})

# Example usage.
df['C'], df['D'] = zip(*df.apply(lambda x: 0 if x['A'] == 1 else some_func(x['A'], x['B']), axis=1))

print(df)

【问题讨论】:

  • 这对于 pandas 来说似乎是非常反模式的。你具体想做什么?因为目前有几种矢量化方法可以创建这些列,这些方法比当前设置的性能更高。
  • @HenryEcker 我有一个非常大的数据集,本质上只想将该函数应用于某些指定的行以进行测试,而其余的行则用零填充。所以基本上我使用 0 if x['A'] != 指定行。
  • 你的函数实际上是 x + y 和 x - y 吗?或者这是否代表了一些更复杂的功能。我很欣赏将问题最小化的尝试,但通常在 pandas 中,重要的是要知道正在发生哪些类型的操作,以确保提供的解决方案尽可能适用于大数据。
  • 您可以按索引位置选择df.iloc[0:20].apply(...) 吗?但同样,这可能会比任何矢量化解决方案都慢,除非您真的只需要前 20 行。
  • 如何让三元运算符的两个条件都返回元组:lambda x: (0, 0) if x['A'] == 1 else some_func(x['A'], x['B'])

标签: python pandas dataframe function apply


【解决方案1】:

你可以做两件事。

一个,正如 Parfait 在 cmets 中建议的那样,您返回一个元组而不是一个整数 - lambda x: (0, 0) if x['A'] == 1 else some_func(x['A'], x['B'])

否则,如果你的逻辑比较复杂,我建议你把你的 if 逻辑移到函数本身。

# A function that returns multiple things.
def some_func(df):
    if df['A'] == 1: # Replace with your condition
        return (None, None) # Return a tuple, with whatever values. I suggest None, but 0 is OK.
    # Some elif logic
    else:
         return x+y, x-y

然后:

df['C'], df['D'] = zip(*df.apply(some_func, axis=1))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2017-09-10
    • 2019-12-15
    • 2018-09-20
    • 2022-12-11
    • 2020-07-16
    • 1970-01-01
    相关资源
    最近更新 更多