簡體   English   中英

在 Pandas DataFrame 中創建一個具有特定值的列

[英]Create a column with particular value in pandas DataFrame

我有 DataFrame 列authorauthor姓名)、 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 

創建我的 DataFrame 的代碼:

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)

使用帶有reindex pivot表來添加缺失的列:

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

set_indexunstack

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

您正在尋找的可以通過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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM