如何在 pandas 系列中计算连续重复值

6
请考虑以下系列,ser
date        id 
2000        NaN
2001        NaN 
2001        1
2002        1
2000        2
2001        2
2002        2
2001        NaN
2010        NaN
2000        1
2001        1
2002        1
2010        NaN

如何计算值,以便计数并返回每个连续数字?谢谢。

Count
NaN     2 
1       2 
2       3
NaN     2
1       3
NaN     1

这是您正在寻找的吗?这里 - Guy
@Guy,它似乎不起作用。可能是因为nan的缘故。 - Oli
1
这基本上是运行长度编码。当您使用您喜欢的搜索引擎查找时,您可能会找到一些实现方式;) - swenzel
请查看此处的答案:https://stackoverflow.com/questions/46572023/run-length-encoding-python - venkata krishnan
1
@sophros,棘手的部分是NaN,这些答案/问题都无法处理。 - Andy Hayden
2个回答

5
累加技巧在这里非常有用,不过由于NaN值需要特殊处理,所以我认为您需要单独处理它们:
In [11]: df.id.isnull() & df.id.shift(-1).isnull()
Out[11]:
0      True
1     False
2     False
3     False
4     False
5     False
6     False
7      True
8     False
9     False
10    False
11    False
12     True
Name: id, dtype: bool

In [12]: df.id.eq(df.id.shift(-1))
Out[12]:
0     False
1     False
2      True
3     False
4      True
5      True
6     False
7     False
8     False
9      True
10     True
11    False
12    False
Name: id, dtype: bool

In [13]: (df.id.isnull() & df.id.shift(-1).isnull()) | (df.id.eq(df.id.shift(-1)))
Out[13]:
0      True
1     False
2      True
3     False
4      True
5      True
6     False
7      True
8     False
9      True
10     True
11    False
12     True
Name: id, dtype: bool

In [14]: ((df.id.isnull() & df.id.shift(-1).isnull()) | (df.id.eq(df.id.shift(-1)))).cumsum()
Out[14]:
0     1
1     1
2     2
3     2
4     3
5     4
6     4
7     5
8     5
9     6
10    7
11    7
12    8
Name: id, dtype: int64

现在你可以在groupby中使用此标签:

In [15]: g = df.groupby(((df.id.isnull() & df.id.shift(-1).isnull()) | (df.id.eq(df.id.shift(-1)))).cumsum())

In [16]: pd.DataFrame({"count": g.id.size(), "id": g.id.nth(0)})
Out[16]:
    count   id
id
1       2  NaN
2       2  1.0
3       1  2.0
4       2  2.0
5       2  NaN
6       1  1.0
7       2  1.0
8       1  NaN

1
输出与问题的输出不匹配。 - Oli
1
@Oli 是的,但非常接近并且特别地,OP的输出有重复项(和NaN)在索引中,通过reset_index()会变成一样的... - Andy Hayden
2
同意Andy的观点:唯一索引具有显著的性能优势。此外,作为“索引”,它更加合理。 - jpp

5

这里有另一种方法,使用fillna来处理NaN值:

s = df.id.fillna('nan')
mask = s.ne(s.shift())

ids = s[mask].to_numpy()
counts = s.groupby(mask.cumsum()).cumcount().add(1).groupby(mask.cumsum()).max().to_numpy()

# Convert 'nan' string back to `NaN`
ids[ids == 'nan'] = np.nan
ser_out = pd.Series(counts, index=ids, name='counts')

[输出]

nan    2
1.0    2
2.0    3
nan    2
1.0    3
nan    1
Name: counts, dtype: int64

美丽的。谢谢 - Oli
我们能否在最后将字符串“nan”替换回双精度“nan”? - Oli
1
如果将输出分配给一个新变量ser_out,类似于ser_out.index = ser_out.index.where(ser_out.index != 'nan')这样的东西可能会出现吗?或者更好的方法是,在Series构造函数之前使用ids[ids == 'nan'] = np.nan - Chris Adams

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接