在 DataFrame.pivot() 上,结果与我的预期不同

发布于 2025-01-15 05:57:28 字数 713 浏览 1 评论 0原文

我指的是 https://github.com/pandas-dev/pandas/tree/main/doc/cheatsheet

如您所见,如果我使用 pivot(),则所有值都位于第 0 行和第 1 行中。

如果我使用pivot(),结果有所不同,如下所示。

pivot() 之前的 DataFrame:

在此处输入图像描述

pivot() 之后的数据帧:

在此处输入图像描述

这个结果是故意的吗?

I'm referring to
https://github.com/pandas-dev/pandas/tree/main/doc/cheatsheet.

enter image description here

As you can see, if I use pivot(), then all values are in row number 0 and 1.

But if I do use pivot(), the result was different like below.

DataFrame before pivot():

enter image description here

DataFrame after pivot():

enter image description here

Is the result on purpose?

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

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

发布评论

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

评论(1

胡渣熟男 2025-01-22 05:57:28

在您的数据中,灰色列(行的索引)丢失:

df = pd.DataFrame({'variable': list('aaabbbccc'), 'value': range(9)})
print(df)

# Output
  variable  value
0        a      0
1        a      1
2        a      2
3        b      3
4        b      4
5        b      5
6        c      6
7        c      7
8        c      8

添加灰色列:

df['grey'] = df.groupby('variable').cumcount()
print(df)

# Output
  variable  value  grey
0        a      0     0
1        a      1     1
2        a      2     2
3        b      3     0
4        b      4     1
5        b      5     2
6        c      6     0
7        c      7     1
8        c      8     2

现在您可以旋转:

df = df.pivot('grey', 'variable', 'value')
print(df)

# Output
variable  a  b  c
grey             
0         0  3  6
1         1  4  7
2         2  5  8

花时间阅读 如何旋转数据框?

In your data, the grey column (index of the row) is missing:

df = pd.DataFrame({'variable': list('aaabbbccc'), 'value': range(9)})
print(df)

# Output
  variable  value
0        a      0
1        a      1
2        a      2
3        b      3
4        b      4
5        b      5
6        c      6
7        c      7
8        c      8

Add the grey column:

df['grey'] = df.groupby('variable').cumcount()
print(df)

# Output
  variable  value  grey
0        a      0     0
1        a      1     1
2        a      2     2
3        b      3     0
4        b      4     1
5        b      5     2
6        c      6     0
7        c      7     1
8        c      8     2

Now you can pivot:

df = df.pivot('grey', 'variable', 'value')
print(df)

# Output
variable  a  b  c
grey             
0         0  3  6
1         1  4  7
2         2  5  8

Take the time to read How can I pivot a dataframe?

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