我有一个这样的df:
Count
1
0
1
1
0
0
1
1
1
0如果1在Count中连续出现两次或两次以上,我希望在新列中返回一个1,如果没有,则返回一个0。因此,在新的列中,根据列Count中满足的条件,每一行都将获得一个1。我想要的输出结果是:
Count New_Value
1 0
0 0
1 1
1 1
0 0
0 0
1 1
1 1
1 1
0 0我在想我可能需要使用itertools,但我一直在读到它,还没有遇到我需要的东西。我希望能够使用这个方法来计算连续出现的次数,而不仅仅是2次。例如,有时我需要计算10个连续出现的次数,我在这里的示例中只使用2。
发布于 2016-06-21 10:39:32
您可以:
df['consecutive'] = df.Count.groupby((df.Count != df.Count.shift()).cumsum()).transform('size') * df.Count要获得以下信息:
Count consecutive
0 1 1
1 0 0
2 1 2
3 1 2
4 0 0
5 0 0
6 1 3
7 1 3
8 1 3
9 0 0在这里,您可以对任何阈值执行以下操作:
threshold = 2
df['consecutive'] = (df.consecutive > threshold).astype(int)要获得以下信息:
Count consecutive
0 1 0
1 0 0
2 1 1
3 1 1
4 0 0
5 0 0
6 1 1
7 1 1
8 1 1
9 0 0或者,在一个步骤中:
(df.Count.groupby((df.Count != df.Count.shift()).cumsum()).transform('size') * df.Count >= threshold).astype(int)在效率方面,当问题的规模增长时,使用pandas方法可以显著加快速度:
df = pd.concat([df for _ in range(1000)])
%timeit (df.Count.groupby((df.Count != df.Count.shift()).cumsum()).transform('size') * df.Count >= threshold).astype(int)
1000 loops, best of 3: 1.47 ms per loop对比:
%%timeit
l = []
for k, g in groupby(df.Count):
size = sum(1 for _ in g)
if k == 1 and size >= 2:
l = l + [1]*size
else:
l = l + [0]*size
pd.Series(l)
10 loops, best of 3: 76.7 ms per loop发布于 2016-06-21 10:32:13
不确定这是否经过优化,但你可以试一试:
from itertools import groupby
import pandas as pd
l = []
for k, g in groupby(df.Count):
size = sum(1 for _ in g)
if k == 1 and size >= 2:
l = l + [1]*size
else:
l = l + [0]*size
df['new_Value'] = pd.Series(l)
df
Count new_Value
0 1 0
1 0 0
2 1 1
3 1 1
4 0 0
5 0 0
6 1 1
7 1 1
8 1 1
9 0 0https://stackoverflow.com/questions/37934399
复制相似问题