Pandas:如何提取已分组的数据

发布于 2025-01-09 03:13:35 字数 507 浏览 1 评论 0原文

以下是演示我的问题的示例代码:

import numpy as np
import pandas as pd

np.random.seed(10)

df = pd.DataFrame(np.random.randint(0,10,size=(100, 2)), columns=list('xy'))

df

    x   y
0   9   4
1   0   1
2   9   0
3   1   8
4   9   0
... ... ...
95  0   4
96  6   4
97  9   8
98  0   7
99  1   7

groups = df.groupby(['x'])

groups.size()

x
0    11
1    12
2    15
3    13
4    14
5     5
6     6
7     9
8     5
9    10
dtype: int64

如何将 x 值作为一列进行访问,将聚合的 y 值作为第二列进行访问,以绘制 x 与 y 的关系图?

Here is an example code to demonstrate my problem:

import numpy as np
import pandas as pd

np.random.seed(10)

df = pd.DataFrame(np.random.randint(0,10,size=(100, 2)), columns=list('xy'))

df

    x   y
0   9   4
1   0   1
2   9   0
3   1   8
4   9   0
... ... ...
95  0   4
96  6   4
97  9   8
98  0   7
99  1   7

groups = df.groupby(['x'])

groups.size()

x
0    11
1    12
2    15
3    13
4    14
5     5
6     6
7     9
8     5
9    10
dtype: int64

How can I access the x-values as a column and the aggregated y-values as a second column to plot x versus y?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

和我恋爱吧 2025-01-16 03:13:35

两个选择。

  1. 使用 reset_index()
groups = df.groupby(['x']).size().reset_index(name='size')
  1. as_index=False 添加到 groupby
groups = df.groupby(['x'], as_index=False).size()

两者的输出:

>>> groups
   x  size
0  0    16
1  1     9
2  2     9
3  3     5
4  4     7
5  5    10
6  6    10
7  7     7
8  8    12
9  9    15

Two options.

  1. Use reset_index():
groups = df.groupby(['x']).size().reset_index(name='size')
  1. Add as_index=False to groupby:
groups = df.groupby(['x'], as_index=False).size()

Output for both:

>>> groups
   x  size
0  0    16
1  1     9
2  2     9
3  3     5
4  4     7
5  5    10
6  6    10
7  7     7
8  8    12
9  9    15
゛时过境迁 2025-01-16 03:13:35

IIUC,使用 as_index=False

groups = df.groupby(['x'], as_index=False)
out = groups.size()
out.plot(x='x', y='size')

如果只想绘图,也可以将 x 保留为索引:

df.groupby(['x']).size().plot()

输出:

   x  size
0  0    16
1  1     9
2  2     9
3  3     5
4  4     7
5  5    10
6  6    10
7  7     7
8  8    12
9  9    15

在此处输入图像描述

IIUC, use as_index=False:

groups = df.groupby(['x'], as_index=False)
out = groups.size()
out.plot(x='x', y='size')

If you only want to plot, you can also keep the x as index:

df.groupby(['x']).size().plot()

output:

   x  size
0  0    16
1  1     9
2  2     9
3  3     5
4  4     7
5  5    10
6  6    10
7  7     7
8  8    12
9  9    15

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文