如何只打印Category列[没有其他列]?

问题描述 投票:-1回答:1

我想访问给定数据框中的类别但无法获取它。 “如何只打印类别列?”

此代码显示计数中只有一列,但我也想访问类别,用于分组数据。

enter image description here

python pandas dataframe pandas-groupby
1个回答
1
投票

您可以使用get_group方法:

In [21]: gb.get_group('foo')
Out[21]: 
     A         B   C
0  foo  1.624345   5
2  foo -0.528172  11
4  foo  0.865408  14

注意:这不需要为每个组创建每个子数据帧的中间字典/副本,因此使用dict(iter(gb))创建天真字典会更加节省内存。这是因为它使用了groupby对象中已有的数据结构。

您可以使用groupby切片选择不同的列:

In [22]: gb[["A", "B"]].get_group("foo")
Out[22]:
     A         B
0  foo  1.624345
2  foo -0.528172
4  foo  0.865408

In [23]: gb["C"].get_group("foo")
Out[23]:
0     5
2    11
4    14
Name: C, dtype: int64
© www.soinside.com 2019 - 2024. All rights reserved.