根据其他列创建表示特定值历史存在的列。

问题描述 投票:2回答:2

假设我有 df 以下。

df = pd.DataFrame({
    'A': ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'],
    'B': [False, True, False, False, True, False, False, True]
})

df 已按以下方式排序 A 显然)和时间(降)。因此,对于每个由 A,这些线索在 B 是按时间降序排列的。我想做的是在一个列中添加一个 C 其中,对每组而言,是 True 如果有 True 价值 B 在过去。结果会是这样的。

    A   B       C
0   a   False   True
1   a   True    False
2   a   False   False
3   a   False   False
4   b   True    True
5   b   False   True
6   b   False   True
7   b   True    False

我怀疑我需要使用 groupby()idxmax() 但一直无法使其工作。有什么好办法吗?

python pandas dataframe pandas-groupby
2个回答
3
投票

IIUC这里有一个方法。

rev_cs = df[::-1].groupby('A').B.apply(lambda x: x.cumsum().shift(fill_value=0.).gt(0))
df['C'] = rev_cs[::-1]

print(df)

  A      B      C
0  a  False   True
1  a   True  False
2  a  False  False
3  a  False  False
4  b   True   True
5  b  False   True
6  b  False   True
7  b   True  False

3
投票

IIUC idxmax 是这样 transform

df['New']=df.index<df.iloc[::-1].groupby('A').B.transform('idxmax').sort_index()
df
   A      B    New
0  a  False   True
1  a   True  False
2  a  False  False
3  a  False  False
4  b   True   True
5  b  False   True
6  b  False   True
7  b   True  False

如果都是假的

s1=df.index<df.iloc[::-1].groupby('A').B.transform('idxmax').sort_index()
s2=df.groupby('A').B.transform('any')
df['New']=s1&s2
© www.soinside.com 2019 - 2024. All rights reserved.