Dataframe python,其中条件考虑了前一行条件

2024-06-17 12:50:52 发布

您现在位置:Python中文网/ 问答频道 /正文

:)

我有这样一个数据帧(它是整个数据帧的摘录):

a   b
1   1   
6   3
7   5   
1   7
12  5
12  5   
2   5
95  2   
44  3

考虑到前面的条件,我想在python中基于多个where条件使用NumPy创建一个新列。让我举例说明:

我想在以下情况下创建值为“1”的列“C”:

(a > b) and (a[-1] < b) and (the previous valued value of "c" must be 2)

另一个条件是“C”=“2”:

(a < b) and (the previous valued value of "c" must be 1)

谢谢你


Tags: andofthe数据numpyvalue情况be
1条回答
网友
1楼 · 发布于 2024-06-17 12:50:52

您可以使用^{}返回从choicelist中的元素绘制的数组,具体取决于条件。 使用:

df['c'] = '' #  > assign initial value
conditions = [
    (df['a'].gt(df['b']) & df['a'].shift().lt(df['b'])) & (df['c'].shift().eq('') | df['c'].shift().eq(2)),
    df['a'].lt(df['b']) & (df['c'].shift().eq(1) | df['c'].shift().eq(''))
]

choices = [1, 2]
df['c'] = np.select(conditions, choices, default='')
print(df)

这张照片是:

    a  b  c
0   1  1   
1   6  3  1
2   7  5   
3   1  7  2
4  12  5  1
5  12  5   
6   2  5  2
7  95  2   
8  44  3   

相关问题 更多 >