python - 在 Pandas 列中,如何找到特定值出现的最大连续行数?

标签 python pandas dataframe feature-engineering

假设我们有以下带有列名的 df。

df = pd.DataFrame({
    'names':['Alan', 'Alan', 'John', 'John', 'Alan', 'Alan','Alan', np.nan, np.nan, np.nan, np.nan, np.nan, 'Christy', 'Christy','John']})
>>> df
      names
0      Alan
1      Alan
2      John
3      John
4      Alan
5      Alan
6      Alan
7       NaN
8       NaN
9       NaN
10      NaN
11      NaN
12  Christy
13  Christy
14     John

我想在返回特定值出现的最大连续次数的列上运行应用函数。起初,我想为 NaN 执行此操作,但推而广之,我想切换到列中的任何其他值。

解释: 如果我们运行 Nan 申请,结果将是 5,因为 5 是 NaN 连续出现的最高次数。如果列中其他值之后有后续行,然后 NaN 连续出现 gt 超过 5 次,那么结果就是这样。

如果我们为 Alan 运行申请,结果将是 3,因为 3 将在连续 Alan 的第一次出现时取代 2。

最佳答案

df_counts = df #create new df to keep the original
df_counts['names'].fillna("NaN", inplace=True) # replace np.nan with string
df_counts['counts'] = df.names.groupby((df.names != df.names.shift()).cumsum()).transform('size') # count consecutive names
df_counts = df_counts.sort_values('counts').drop_duplicates("names",keep='last') #keep only the highest counts

def get_counts(name):
  return df_counts.loc[df['names'] == name, 'counts'].item()

然后 get_counts("Alan") 将返回 3,而 get_counts("NaN") 将返回 5.

关于python - 在 Pandas 列中,如何找到特定值出现的最大连续行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66483359/

相关文章:

python - "sorted 1-d iterator"基于 "2-d iterator"(迭代器的笛卡尔积)

python - Python 中的日期时间触发器?

python - pandas groupby 访问最后一组

python - mongo的分组结果到pandas DataFrame

python - 从python pandas中的列名获取列索引

python - 尝试运行测试时 Pytest 给我一个错误

python - 删除空行 - openpyxl

python - 将非空值向前传播到最后一个条目

python - 在 python 中为数据框中的缺失值创建指标

python - pandas 聚合数据到一个 numpy 数组 : data structure conversion