gpt4 book ai didi

python - 我将如何使用 pandas 旋转这个基本表?

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

enter image description here

我想要的是:

visit_id   atc_1   atc_2    atc_3     atc_4     atc_5  atc_6  atc_7
48944282 A02AG J01CA04 J095AX02 N02BE01 R05X NaN NaN
48944305 A02AG A03AX13 N02BE01 R05X NaN NaN NaN

我不知道需要提前多少个 atc_1...atc_7...?atc_100 列。我只需要将所有关联的 atc_codes 与每个 visit_id 一起收集到一行中。

这看起来像是一个group_by 然后是一个pivot 但我已经尝试了很多次但都失败了。我还尝试使用 pandas 的 merge() 自行加入 la SQL,但这也不起作用。

最后的结果是我将atc_1, atc_7, ... atc_100 粘贴在一起形成一个长长的atc_code。这个复合 atc_code 将是我试图预测的数据集的“Y”或“标签”列。

谢谢!

最佳答案

使用cumcount首先是按函数创建列的每组计数值 pivot .然后使用 reindex_axis 添加缺失的列并通过 add_prefix 更改列名.最后 reset_index :

g = df.groupby('visit_id').cumcount() + 1
print (g)
0 1
1 2
2 3
3 4
4 5
5 1
6 2
7 3
8 4
dtype: int64

df = pd.pivot(index=df['visit_id'], columns=g, values=df['atc_code'])
.reindex_axis(range(1, 8), 1)
.add_prefix('atc_')
.reset_index()

print (df)
visit_id atc_1 atc_2 atc_3 atc_4 atc_5 atc_6 atc_7
0 48944282 A02AG J01CA04 J095AX02 N02BE01 R05X NaN NaN
1 48944305 A02AG A03AX13 N02BE01 R05X None NaN NaN

关于python - 我将如何使用 pandas 旋转这个基本表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44041772/

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