gpt4 book ai didi

python-3.x - Groupby,转置和追加 Pandas ?

转载 作者:行者123 更新时间:2023-12-04 11:11:08 29 4
gpt4 key购买 nike

我有一个看起来像这样的数据框:

enter image description here



每个用户有 10 条记录。现在,我想创建一个如下所示的数据框:
userid  name1  name2  ... name10

这意味着我需要反转列的每 10 条记录 name并附加到一个新的数据帧。

那么,它是如何做到的呢?有什么办法可以在 Pandas 中做到吗?

最佳答案

groupby('userid') 然后是每个组内的 reset_index 以在组间一致地枚举。然后 unstack 获取列。

df.groupby('userid')['name'].apply(lambda df: df.reset_index(drop=True)).unstack()

示范
df = pd.DataFrame([
[123, 'abc'],
[123, 'abc'],
[456, 'def'],
[123, 'abc'],
[123, 'abc'],
[456, 'def'],
[456, 'def'],
[456, 'def'],
], columns=['userid', 'name'])

df.sort_values('userid').groupby('userid')['name'].apply(lambda df: df.reset_index(drop=True)).unstack()

enter image description here

如果您不想将 userid 作为索引,请将 reset_index 添加到末尾。
df.sort_values('userid').groupby('userid')['name'].apply(lambda df: df.reset_index(drop=True)).unstack().reset_index()

enter image description here

关于python-3.x - Groupby,转置和追加 Pandas ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38369424/

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