我修改了一些丑陋的代码来处理这个问题,但想找出一种pythonic的方式:

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],'price_B':[1,1,1,4,4,4,4,0,2,2,2,5,5,5,]})

我想创建“Price_B”列。对于每个“产品”子组,如果“信号”为 1,Price_B 等于价格。如果信号为 0,Price_B 等于前一行的价格。如果子组以 0“信号”开始,则“price_B”将保持为 0 直到“信号'变为 1。

以下是我写的:
dfb = df.groupby('product').get_group('B')
for i in dfb.index:
    if dfb.loc[i, 'signal'] == 1:
        dfb.loc[i, 'test'] = dfb.loc[i, 'price']
    else:
        try:
            dfb.loc[i, 'test'] = dfb.loc[i - 1, 'test']
        except KeyError:
            dfb.loc[i, 'test'] = 0

我知道这些代码是不合法的。有人可以帮忙吗?

最佳答案

我会使用 pd.Series.where 来使信号不是 1 的数据无效。然后向前填充和填充na。

def f(d):
    dtype = d.price.dtype
    p = d.price.where(d.signal.eq(1))
    return p.ffill().fillna(0).astype(dtype)

df.assign(price_B=df.groupby('product', group_keys=False).apply(f))

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

关于python - 带条件的 Pandas 按行转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45239722/

10-10 00:56