如何为数据创建三个新列?

2024-04-25 14:03:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些数据

tweet_id               worker_id    option
397921751801147392  A1DZLZE63NE1ZI  pro-vaccine
397921751801147392  A3UJO2A7THUZTV  pro-vaccine
397921751801147392  A3G00Q5JV2BE5G  pro-vaccine
558401694862942208  A1G94QON7A9K0N  other
558401694862942208  ANMWPCK7TJMZ8   other

我想要的是每个tweet id只有一行,三个6列标识worker id和选项。你知道吗

它的期望输出类似于

tweet_id              worker_id_1  option_1     worker_id_2    option_2     worker_id_3    option 3
397921751801147392 A1DZLZE63NE1ZI pro-vaccine A3UJO2A7THUZTV pro_vaccine A3G00Q5JV2BE5G pro_vaccine

我怎样才能做到这一点与熊猫?你知道吗


Tags: 数据id选项标识protweetworkeroption
1条回答
网友
1楼 · 发布于 2024-04-25 14:03:36

这是关于将数据从长格式改为宽格式。您可以创建一个分组的count列作为id以作为新的列标题展开,然后使用pivot_table(),最后通过将多层粘贴在一起来重命名这些列。你知道吗

df['count'] = df.groupby('tweet_id').cumcount() + 1
df1 = df.pivot_table(values = ['worker_id', 'option'], index = 'tweet_id', 
                     columns = 'count', aggfunc='sum')
df1.columns = [x + "_" + str(y) for x, y in df1.columns]

enter image description here


pivot_table()的另一个选项是unstack()

df['count'] = df.groupby('tweet_id').cumcount() + 1
df1 = df.set_index(['tweet_id', 'count']).unstack(level = 1)
df1.columns = [x + "_" + str(y) for x, y in df1.columns]

enter image description here

相关问题 更多 >