Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫系列添加上一行的条件_Python_Pandas_Dataframe - Fatal编程技术网

Python 熊猫系列添加上一行的条件

Python 熊猫系列添加上一行的条件,python,pandas,dataframe,Python,Pandas,Dataframe,只有在当前单元格中的条件匹配时,我才需要添加具有前几行的序列。以下是数据帧: import pandas as pd data = {'col1': [1, 2, 1, 0, 0, 0, 0, 3, 2, 2, 0, 0]} df = pd.DataFrame(data, columns=['col1']) df['continuous'] = df.col1 print(df) 我需要+1一个单元格,如果它的值>0否则-1,则该

只有在当前单元格中的条件匹配时,我才需要添加具有前几行的序列。以下是数据帧:

import pandas as pd
        data = {'col1': [1, 2, 1, 0, 0, 0, 0, 3, 2, 2, 0, 0]}
        df = pd.DataFrame(data, columns=['col1'])
        df['continuous'] = df.col1
        print(df)
我需要
+1
一个单元格,如果它的
值>0
否则
-1
,则该单元格具有上一个和。所以,我期待的结果是

   col1  continuous
0      1           1//+1 as its non-zero
1      2           2//+1 as its non-zero
2      1           3//+1 as its non-zero
3      0           2//-1 as its zero
4      0           1
5      0           0
6      0           0// not to go less than 0
7      3           1
8      2           2
9      2           3
10     0           2
11     0           1

案例2:如果我不想使用
>0
,我需要
,您可以使用布尔函数上的
cumsum
来执行此操作:

只要
col1
不是零,就给我一个+1:

(df.col1 != 0 ).cumsum()
只要
col1
为零,就给我一个-1:

- (df.col1 == 0 ).cumsum()
然后把它们加在一起

df['continuous'] = (df.col1 != 0 ).cumsum() - (df.col1 == 0 ).cumsum()

但是,这并不能解决您提到的降到零以下的标准。对我来说,这里的关键问题是控制输出不降到零以下。考虑到这一点,我们可以在输出为负值时屏蔽输出,并进行相应调整:

# a little longer data for corner case
df = pd.DataFrame({'col1': [1, 2, 1, 0, 0, 0, 0, 3, 2, 2, 0, 0,0,0,0,2,3,4]})


s = df.col1.gt(0)
out = s.where(s,-1).cumsum()
df['continuous'] = out - out.where((out<0)&(~s)).ffill().fillna(0)

回答你的问题了吗?@erentknn看起来很有希望,正在检查..为什么最后两行是
0
?他们是否应该被
2,1
?@QuangHoang更正。这与rhug对
clip
的建议相结合:
df['continuous']=((df.col1!=0).cumsum()-(df.col1==0.cumsum()).clip(0)
谢谢。amended@DavidErickson如果我有100个起始行作为0,则此答案不起作用。然后接下来100行值大于0的行仍将为0(剪裁)。@SachinVerma in你能用额外的零来更新你的问题吗?@DavidErickson是的,检查索引6。
# a little longer data for corner case
df = pd.DataFrame({'col1': [1, 2, 1, 0, 0, 0, 0, 3, 2, 2, 0, 0,0,0,0,2,3,4]})


s = df.col1.gt(0)
out = s.where(s,-1).cumsum()
df['continuous'] = out - out.where((out<0)&(~s)).ffill().fillna(0)
    col1 continuous
0      1          1
1      2          2
2      1          3
3      0          2
4      0          1
5      0          0
6      0          0
7      3          1
8      2          2
9      2          3
10     0          2
11     0          1
12     0          0
13     0          0
14     0          0
15     2          1
16     3          2
17     4          3