【发布时间】:2023-03-11 05:45:02
【问题描述】:
我想打印与 Pandas 分组的结果。
我有一个数据框:
import pandas as pd
df = pd.DataFrame({'A': ['one', 'one', 'two', 'three', 'three', 'one'], 'B': range(6)})
print(df)
A B
0 one 0
1 one 1
2 two 2
3 three 3
4 three 4
5 one 5
在按“A”分组后打印时,我有以下内容:
print(df.groupby('A'))
<pandas.core.groupby.DataFrameGroupBy object at 0x05416E90>
如何打印分组的数据框?
如果我这样做:
print(df.groupby('A').head())
我获得的数据框好像没有分组一样:
A B
A
one 0 one 0
1 one 1
two 2 two 2
three 3 three 3
4 three 4
one 5 one 5
我期待的是这样的:
A B
A
one 0 one 0
1 one 1
5 one 5
two 2 two 2
three 3 three 3
4 three 4
【问题讨论】:
-
我用
print df.groupby('A').head()得到了正确的输出。你有什么版本的熊猫? -
我刚刚在台式机和笔记本电脑上更新到 0.13.1。
-
如何直接“列出()”对象?然后您可以将其作为普通数据结构进行操作/打印。
-
据我所知,没有一个答案能够产生所需的输出。对于这个特定示例,我能找到的最接近的是
df.groupby(['A', 'B']).sum(),但如果('A', 'B')对不是唯一的,它将失败。 -
你好。我可以知道如何仅在输出中打印 "one" 、 "two" 、 "three" 吗?我的意思是只打印我们分组的数据。我想用这些数据来标记我的饼图。