gpt4 book ai didi

python - 使用分组数据 reshape Pandas Dataframe(从长到宽)

转载 作者:太空宇宙 更新时间:2023-11-04 00:42:34 25 4
gpt4 key购买 nike

假设我有以下格式的数据:

group_id | entity_id | value
A a1 5
A a2 3
A a3 2
B b1 10
B b2 8
B b3 11
C c1 2
C c2 6
C c3 NaN

表 1.

因此,保证每个组 (A/B/C) 将有 3 个实体。每个实体都有一个对应的值(如果不存在,有时为 NaN)。

我想将这些数据从现有格式 reshape 为...:

group_id | entity_1 | entity_2 | entity_3
A 5 3 2
B 10 8 11
C 2 6 NaN

表 2.

其中entity_1/entity_2/entity_3分别对应a1/a2/a3(或b1/b2/b3,c1/c2/c3)。

我该怎么做?

我找到的一个解决方案是使用 pivot 函数,所以...

df.pivot(index='group_id', columns='entity_id', values='value')

但据我所知,问题在于生成的 reshape 数据透视表中实体的列将不是我在表 2 中想要的格式——这对于我正在处理的一些下游内容很重要处理数据。

我可能会问一个愚蠢的问题,但我很难找到使用现有的枢轴/融合函数以我上面描述的方式从长到宽的方法。谁能帮帮我?

如有必要,我很乐意提供更多详细信息,请告诉我!

最佳答案

您可以使用 pivot新列是 indexing with str 提取的 entity_id 列的最后一个值:

df = pd.pivot(index=df.group_id, columns=df.entity_id.str[-1], values=df.value)
.add_prefix('entity_')
.rename_axis(None, axis=1)
.reset_index()
print (df)
group_id entity_1 entity_2 entity_3
0 A 5.0 3.0 2.0
1 B 10.0 8.0 11.0
2 C 2.0 6.0 NaN

解决方案 cumcount :

df = pd.pivot(index=df.group_id,
columns=df.groupby('group_id').cumcount() + 1,
values=df.value)
.add_prefix('entity_')
.reset_index()
print (df)
group_id entity_1 entity_2 entity_3
0 A 5.0 3.0 2.0
1 B 10.0 8.0 11.0
2 C 2.0 6.0 NaN

另一种解决方案 groupbyapply,最后由 unstack reshape :

df = df.groupby("group_id")["value"]
.apply(lambda x: pd.Series(x.values))
.unstack()
.add_prefix('entity_')
.reset_index()
print (df)
group_id entity_0 entity_1 entity_2
0 A 5.0 3.0 2.0
1 B 10.0 8.0 11.0
2 C 2.0 6.0 NaN

如果需要从1开始计数:

df = df.groupby("group_id")["value"].apply(lambda x: pd.Series(x.values))
.unstack()
.rename(columns = lambda x: x+1)
.add_prefix('entity_')
.reset_index()
print (df)
group_id entity_1 entity_2 entity_3
0 A 5.0 3.0 2.0
1 B 10.0 8.0 11.0
2 C 2.0 6.0 NaN

关于python - 使用分组数据 reshape Pandas Dataframe(从长到宽),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41236423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com