重塑Pandas DataFrame:从一列创建多个列

发布于 2025-02-06 16:05:08 字数 200 浏览 1 评论 0原文

我想重塑图形数据框

​//i.sstatic.net/kzqla.png“ alt =“在此处输入图像描述”>

有人可以帮我吗?

I would like to reshape the folowing dataframe

enter image description here

into

enter image description here

Could somebody help me with that?

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

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

发布评论

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

评论(2

素染倾城色 2025-02-13 16:05:08

您是否尝试过df.pivot()pd.pivot()?列C中的值将成为列标题。之后,将多指数列缩放并重命名它们。

import pandas as pd

#df = df.pivot(['A', 'B'], columns='C').reset_index()    #this also works
df = pd.pivot(data=df, index=['A', 'B'], columns='C').reset_index()
df.columns = ['A', 'B', 'X', 'Y']
print(df)

有时输出

   A   B  X  Y
0  a  aa  1  5
1  b  bb  6  2
2  c  cc  3  7
3  d  dd  8  4

可能会有具有相同索引的重复记录,然后您必须改用pd.pivot_table()。 param aggfunc = np.mean将占据这些重复记录的平均值,并成为从输出中看到的float

import pandas as pd
import numpy as np

df = pd.pivot_table(data=df, index=['A', 'B'], columns='C', aggfunc=np.mean).reset_index()
df.columns = ['A', 'B', 'X', 'Y']
print(df)

输出

   A   B    X    Y
0  a  aa  1.0  5.0
1  b  bb  6.0  2.0
2  c  cc  3.0  7.0
3  d  dd  8.0  4.0

Have you tried df.pivot() or pd.pivot()? The values in column C will become column headers. After that, flatten the multi-index columns, and rename them.

import pandas as pd

#df = df.pivot(['A', 'B'], columns='C').reset_index()    #this also works
df = pd.pivot(data=df, index=['A', 'B'], columns='C').reset_index()
df.columns = ['A', 'B', 'X', 'Y']
print(df)

Output

   A   B  X  Y
0  a  aa  1  5
1  b  bb  6  2
2  c  cc  3  7
3  d  dd  8  4

Sometimes, there might be repeated records with the same index, then you'd have to use pd.pivot_table() instead. The param aggfunc=np.mean will take the mean of these repeated records, and become type float as you can see from the output.

import pandas as pd
import numpy as np

df = pd.pivot_table(data=df, index=['A', 'B'], columns='C', aggfunc=np.mean).reset_index()
df.columns = ['A', 'B', 'X', 'Y']
print(df)

Output

   A   B    X    Y
0  a  aa  1.0  5.0
1  b  bb  6.0  2.0
2  c  cc  3.0  7.0
3  d  dd  8.0  4.0
他是夢罘是命 2025-02-13 16:05:08

您可以尝试

out = df.pivot(index=['A', 'B'], columns='C', values='D').reset_index()
print(out)

C  A   B  X  Y
0  a  aa  1  5
1  b  bb  6  2
2  c  cc  3  7
3  d  dd  8  4

You can try

out = df.pivot(index=['A', 'B'], columns='C', values='D').reset_index()
print(out)

C  A   B  X  Y
0  a  aa  1  5
1  b  bb  6  2
2  c  cc  3  7
3  d  dd  8  4
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文