【问题标题】:pandas dataframe apply using additional arguments熊猫数据框使用附加参数应用
【发布时间】:2018-01-08 19:02:36
【问题描述】:

下面的例子:

df = pd.DataFrame({'signal':[1,0,0,1,0,0,0,0,1,0,0,1,0,0],'product':['A','A','A','A','A','A','A','B','B','B','B','B','B','B'],'price':[1,2,3,4,5,6,7,1,2,3,4,5,6,7],'price2':[1,2,1,2,1,2,1,2,1,2,1,2,1,2]})

我有一个函数“fill_price”来创建一个基于“信号”和“价格”的新列“Price_B”。对于每个“产品”子组,如果“信号”为 1,Price_B 等于价格。如果信号为 0,Price_B 等于前一行的 Price_B。如果子组以 0“信号”开头,则“价格_B”将保持为 0,直到信号'变成1。

目前我有:

def fill_price(df, signal,price_A):
p = df[price_A].where(df[signal] == 1)
return p.ffill().fillna(0).astype(df[price_A].dtype)

然后使用:

df['Price_B'] = fill_price(df,'signal','price')

但是,我想使用 df.groupby('product').apply() 将此 fill_price 函数分别应用于“product”列的两个子集,并将其应用于“price”和“price2”列.有人可以帮忙吗?

我基本上是想做的:

df.groupby('product',groupby_keys=False).apply(fill_price, 'signal','price2')

【问题讨论】:

  • 这行得通吗? df.groupby('product').apply(lambda x: fill_price(x,'signal','price'))

标签: python pandas group-by apply


【解决方案1】:

IIUC,你可以使用这个语法:

df['Price_B'] = df.groupby('product').apply(lambda x: fill_price(x,'signal','price2')).reset_index(level=0, drop=True)

输出:

    price  price2 product  signal  Price_B
0       1       1       A       1        1
1       2       2       A       0        1
2       3       1       A       0        1
3       4       2       A       1        2
4       5       1       A       0        2
5       6       2       A       0        2
6       7       1       A       0        2
7       1       2       B       0        0
8       2       1       B       1        1
9       3       2       B       0        1
10      4       1       B       0        1
11      5       2       B       1        2
12      6       1       B       0        2
13      7       2       B       0        2

不用额外的函数,你可以写得更简单。

df['Price_B'] = (df.groupby('product',as_index=False)
                   .apply(lambda x: x['price2'].where(x.signal==1).ffill().fillna(0))
                   .reset_index(level=0, drop=True))

【讨论】:

  • 它有效。不过,我有点困惑,因为 1. 为什么我们要在末尾重置索引 2. 该函数适用于数据帧,但在 lambda 函数中,我们通过它提供行?谢谢
  • 这是你的函数的构建方式,你返回一个带有索引的数据框,然后 groupby 放置一个新的组索引。是的,您的函数将数据框作为第一个参数,在 lambda 函数中,我们只是将数据框的几行“分组”行传递给您的函数,它返回一个数据框,然后我们将外部索引剥离并让 Pandas 对齐您的原始数据帧与基于原始索引的修改数据帧。
  • @PrintableBao 查看我在没有额外函数调用的情况下用纯 lambda 函数重写的更新。
  • 很棒,看起来更好更容易。你能谈谈 reset_index 和 (level = 0, drop = True) 参数吗?
  • 当您执行 groupby 时,它会在结果数据帧上放置另一个索引级别。但是要将结果分配回原始数据帧,索引非常匹配。因此,您需要删除由 groupby 创建的索引。这就是为什么我要做一个 reset_index(level=0, drop=True)。它通过 groupby 删除新创建的索引级别。
猜你喜欢
  • 1970-01-01
  • 2018-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-14
  • 2018-02-08
  • 2017-06-13
相关资源
最近更新 更多