在DataFram中创建具有特定值的列

2024-10-02 00:36:52 发布

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

我有一个DataFrame列author(作者姓名),hour(作者发布主题时)和number_of_topics(每个作者一小时发布多少主题)。以下是一个例子:

  author hour number_of_topics
0      A  h01                1
1      B  h02                4
2      B  h04                2
3      C  h04                6
4      A  h05                8
5      C  h05                3

我的目标是创建六列(前六个小时),并用主题数量填充它们。我尝试用df.groupby来做这件事,但没有成功。 期望输出:

  author h01 h02 h03 h04 h05 h06
0      A   1   0   0   0   8   0
1      B   0   4   0   2   0   0
2      C   0   0   0   6   3   0 

创建我的数据帧的代码:

import pandas as pd
df = pd.DataFrame({"author":["A","B", "B","C","A","C"],
                   "hour":["h01","h02","h04","h04","h05","h05"],
                   "number_of_topics":["1","4","2","6","8","3"]})
print(df)

Tags: ofnumberdataframedf主题作者authorpd
2条回答

可以通过pivot函数来实现您所寻找的:

df.pivot(index = 'author',columns = 'hour',values = 'number_of_topics').fillna(0)

hour    h01     h02     h04     h05
author              
A       1       0       0       8
B       0       4       2       0
C       0       0       6       3

^{}^{}一起用于添加错误的列:

cols = ['h{:02d}'.format(x) for x in range(1, 7)]
df = (df.pivot('author','hour','number_of_topics')
        .fillna(0)
        .reindex(columns=cols, fill_value=0)
        .reset_index()
        .rename_axis(None, axis=1))
print (df)
  author h01 h02  h03 h04 h05  h06
0      A   1   0    0   0   8    0
1      B   0   4    0   2   0    0
2      C   0   0    0   6   3    0

^{}^{}

cols = ['h{:02d}'.format(x) for x in range(1, 7)]
df = (df.set_index(['author','hour'])['number_of_topics']
        .unstack(fill_value=0)
        .reindex(columns=cols, fill_value=0)
        .reset_index()
        .rename_axis(None, axis=1))
print (df)
  author h01 h02  h03 h04 h05  h06
0      A   1   0    0   0   8    0
1      B   0   4    0   2   0    0
2      C   0   0    0   6   3    0

相关问题 更多 >

    热门问题