Python pandas值\u计数包括groupby之前的所有值
假设我有以下数据帧:Python pandas值\u计数包括groupby之前的所有值,python,pandas,dataframe,count,pandas-groupby,Python,Pandas,Dataframe,Count,Pandas Groupby,假设我有以下数据帧: 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 = 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
任何帮助都将不胜感激 尝试使用:
给出:
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
你能试着扩展一下吗?确切的输出格式是否重要?为什么不直接使用
df.col1.value\u counts()
?
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