【问题标题】:Filtering based on the "rows" data after creating a pivot table in python pandas在 python pandas 中创建数据透视表后基于“行”数据进行过滤
【发布时间】:2013-06-06 18:30:59
【问题描述】:

我有一组从 SQL 数据库中获取并读入 pandas 数据框的数据。生成的 df 大约有 250M 行并且每天都在增长。因此,我想旋转表格以给我一个小得多的表格(几千行)。

桌子看起来像这样,但要大得多:

data

  report_date             item_id        views   category
0  2013-06-01                   2            3          a
1  2013-06-01                   2            2          b
2  2013-06-01                   5           16          a 
3  2013-06-01                   2            4          c
4  2013-06-01                   2            5          d

我想通过忽略“类别”列并仅获取按日期和 item_id 的视图总数来使这个更小。

我正在这样做:

pivot = data.pivot_table(values=['views'], rows=['report_date','item_id'], aggfunc='sum')

                                 views  
report_date item_id
2013-06-01        2                 14           
2013-06-01        5                 16

现在想象一下,随着数据范围持续数月和数千个 item_id,这要大得多。我想选择 item_id = 2 和 report_date 在 '2013-06-01' 和 '2013-06-10' 之间的总浏览量或类似的东西。

我已经连续搜索了几个小时,但看不到如何在“行”(即 report_date 和 item_id)部分中选择和/或过滤掉值。我只能在“值”部分过滤/选择数据(例如:视图)。这个问题很相似,最后提问者评论了我问的同一个问题,但从未得到回答。我只是想尝试引起人们的注意。

Filtering and selecting from pivot tables made with python pandas

感谢所有帮助。这个网站和社区绝对是无价之宝。

【问题讨论】:

    标签: python indexing pandas dataframe


    【解决方案1】:

    你应该可以这样切片:

    In [11]: pivot.ix[('2013-06-01', 3):('2013-06-01', 6)]
    Out[11]:
                         views
    report_date item_id
    2013-06-01  5           16
    

    advance indexing in the docs

    【讨论】:

    • 虽然,something 在这个特定的例子中是可疑的......
    猜你喜欢
    • 2018-09-07
    • 2018-03-31
    • 1970-01-01
    • 2016-07-08
    • 2023-02-24
    • 2019-01-03
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多