简体   繁体   English

熊猫数据透视表与外部列

[英]Pandas Pivot Table with external columns

I have a list with some dates, eg: dates_list=[201701, 201702, 201703, 201704]. 我有一些日期列表,例如:dates_list = [201701,201702,201703,201704]。 This is a user input of desired dates for a specific report. 这是特定报告所需日期的用户输入。

And I have a database with three columns: id, date and value. 我有一个包含三列的数据库:id,date和value。

My database, sometimes, doesn't have records for all dates asked by user(eg: it has only records for 201701 and 201702). 我的数据库有时没有用户询问的所有日期的记录(例如:它只有201701和201702的记录)。 df is my database. df是我的数据库。 I have this command: 我有这个命令:

raw = pd.pivot_table(df, index=['id'],
                         columns=['date'], values=['value'],
                         aggfunc=[np.sum], fill_value=0, margins=False)

Which, of course, will return a pivot table with only two columns: 201701 and 201702. 当然,这将返回仅包含两列的数据透视表:201701和201702。

I want to know if it is possible to use dates_list as columns labels at pivot table construction, in order to return a column full of zeros for 201703 and 201704. If it is not possible, someone know the best approach for this problem? 我想知道是否可以在数据透视表构造中使用dates_list作为列标签,以便返回201703和201704的满列零。如果不可能,有人知道这个问题的最佳方法吗?

Thanks in advance 提前致谢

Sample data: 样本数据:

 df = pd.DataFrame({'id':[1,1,2,1,2],
                    'date': [201701,201701,201701,201702,201702],
                    'value': [0.04, 0.02, 0.07, 0.08, 1.0]})
 df

     date  id  value
0  201701   1   0.04
1  201701   1   0.02
2  201701   2   0.07
3  201702   1   0.08
4  201702   2   1.00

raw = pd.pivot_table(df, index=['id'], columns=['date'], values=['value'],
                     aggfunc=[np.sum], fill_value=0, margins=False)

        sum
  value
date 201701 201702
id
1      0.06   0.08
2      0.07   1.00

date_list = [201701, 201702, 201703, 201704]

raw.reindex(columns=date_list, fill_value=0)

And I got ValueError: Buffer dtype mismatch, expected 'Python object' but got 'long long' 我得到了ValueError:缓冲区dtype不匹配,预期'Python对象'但是'长了'

You can do reindex after pivot_table 你可以在pivot_table之后pivot_table reindex

pd.pivot_table(df, index=['id'],
                         columns=['date'], values=['value'],
                         aggfunc=[np.sum], fill_value=0, margins=False).\
    reindex(columns=[yourlist],fill_value=0)

Update 更新

pd.pivot_table(df, index='id', columns='date', values='value',aggfunc='sum', fill_value=0, margins=False).reindex(columns=[201701,201702,201703])
Out[115]: 
date  201701  201702  201703
id                          
1       0.06    0.08     NaN
2       0.07    1.00     NaN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM