【问题标题】:pandas value_counts include all values before groupbypandas value_counts 包括 groupby 之前的所有值
【发布时间】:2019-03-02 03:17:30
【问题描述】:

假设我有以下数据框:

df = pd.DataFrame([['a',1, -1], ['a', 1, -1], ['b', 0, -1], ['c', -1, -1]] ,columns = ['col1', 'col2', 'col3'])
df
    col1    col2    col3
0   a       1       -1
1   a       1       -1
2   b       0       -1
3   c       -1      -1

现在我想按列对 df 进行分组,并为每个列分别计算 col1 列中值的出现次数。

groupby_df = df.groupby('col1') 
for a,b in groupby_df:
    print("{0} -> \n{1}".format(a, b['col1'].value_counts().sort_index()))

我明白了:

a -> 
a    2
Name: col1, dtype: int64
b -> 
b    1
Name: col1, dtype: int64
c -> 
c    1
Name: col1, dtype: int64

但我想单独统计出现次数,仍然包括所有列值,如下:

a -> 
a    2
b    0
c    0
Name: col1, dtype: int64
b -> 
a    0
b    1
c    0
Name: col1, dtype: int64
c -> 
a    0
b    0
c    1
Name: col1, dtype: int64

任何帮助将不胜感激!

【问题讨论】:

  • 您可以尝试扩展这样做的目的吗?确切的输出格式是否重要?为什么不直接使用df.col1.value_counts()

标签: python pandas dataframe count pandas-groupby


【解决方案1】:

尝试使用.reindex()

import pandas as pd

df = pd.DataFrame([['a',1, -1], ['a', 1, -1], ['b', 0, -1], ['c', -1, -1]] ,columns = ['col1', 'col2', 'col3'])

# Create index using unique values of col1.

uniques = pd.Index(df['col1'].unique())

# Group.

groupby_df = df.groupby('col1')

# Use reindex to assign and autoamtically align the value counts with the index.

for a, b in groupby_df:
    print(b['col1'].value_counts().sort_index().reindex(uniques, fill_value = 0))

给予:

a    2
b    0
c    0
Name: col1, dtype: int64
a    0
b    1
c    0
Name: col1, dtype: int64
a    0
b    0
c    1
Name: col1, dtype: int64

【讨论】:

    猜你喜欢
    • 2020-06-14
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    • 2021-12-13
    • 2018-12-14
    • 1970-01-01
    相关资源
    最近更新 更多