【问题标题】:Python: Pandas shows NaN after passing dictionary to resample()Python:Pandas 在将字典传递给 resample() 后显示 NaN
【发布时间】:2017-06-15 01:07:44
【问题描述】:

这是我拥有的一个非常大的数据框的头部,我已将 publish_datetime 设置为 Pandas 中的索引:

                     sentiment_subjectivity  pos_sentiment_pol
publish_datetime
2016-12-18 16:56:01                  0.2500             0.2500
2016-12-21 16:56:05                  0.0000             0.0000
2016-12-21 16:56:08                  0.0000             0.0000
2016-12-21 16:56:08                  0.1027             0.1027
2016-12-21 16:56:13                  0.0000             0.0000
2016-12-21 16:56:17                  0.0000             0.0000
2016-12-21 16:56:18                  0.1027             0.1027
2016-12-21 16:56:19                  0.1027             0.1027
2016-12-21 16:56:22                  0.1027             0.1027
2016-12-21 16:56:23                  0.1027             0.1027

现在我想重新采样它。我通过传递字典来做到这一点,因为在原始数据框中我还有几个系列。然而结果是一样的:

df = df.resample('1min').apply({'pos_sentiment_pol':'sum'}).fillna('None')

这是我得到的:

                    pos_sentiment_pol
publish_datetime
2016-12-18 16:56:00              0.25
2016-12-18 16:57:00              None
2016-12-18 16:58:00              None
2016-12-18 16:59:00              None
2016-12-18 17:00:00              None
2016-12-18 17:01:00              None
2016-12-18 17:02:00              None
2016-12-18 17:03:00              None
2016-12-18 17:04:00              None
2016-12-18 17:05:00              None

这里有什么问题?

【问题讨论】:

    标签: python pandas dictionary nan resampling


    【解决方案1】:

    索引中的第一个元素来自 3 天前。它会自行分组,而之后的所有内容都会在 3 天后或 4320 分钟后分组。

    这可能是一个错字,或者您想查看它按小时和分钟分组,而不考虑日期。如果后者为真,那么

    df.groupby([df.index.hour, df.index.minute])[['pos_sentiment_pol']].sum()
    
           pos_sentiment_pol
    16 56             0.7635
    

    如果您将第一个索引的值更改为与其余索引相同的日期,那么您的代码可以正常工作

    df.resample('1min').apply({'pos_sentiment_pol':'sum'}).fillna('None')
    
                         pos_sentiment_pol
    publish_datetime                      
    2016-12-21 16:56:00             0.7635
    

    【讨论】:

    • 谢谢。这是数据中的错误数字,我不知道它是如何到达那里的
    猜你喜欢
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 2019-04-02
    • 2019-02-11
    • 1970-01-01
    相关资源
    最近更新 更多