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

时间:2016-12-18 21:22:12

标签: python pandas

我有一些看起来像

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

我想要的是每个推文ID的一行,以及标识工作者ID和选项的三个6列。

所需的输出类似于

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

我怎样才能用熊猫来实现这个目标?

1 个答案:

答案 0 :(得分:2)

这是关于将数据从长格式转换为宽格式。您可以将分组计数列创建为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