【问题标题】:Why is pandas creating NaN for resampling of sql data?为什么 pandas 为 sql 数据的重采样创建 NaN?
【发布时间】:2016-08-10 10:12:17
【问题描述】:

我是 pandas 和 numpy 的新手,我正在尝试将测量值聚合到等间隔的时间序列中。输入数据不是等间距的,看起来像:

timestamp            value  
2016-08-09 11:55:26  1779.510  
2016-08-09 11:55:26  1792.310  
2016-08-09 11:55:27  1796.900  
2016-08-09 11:55:28  1749.760 
2016-08-09 11:55:29  1780.870  
...                  ...

现在我正在尝试从 MySQL 读取数据,然后将其重新采样为等间隔的时间序列。

query = "SELECT timestamp, value FROM iren2.data WHERE data.timestamp >= now() - INTERVAL {0} DAY " \
            "AND data_node_id = {1} ".format(1, 307)

data = pandas.read_sql_query(query, engine, parse_dates=True, index_col='timestamp')
aggregation = pandas.DataFrame()
aggregation['value'] = data.resample('1min').mean()
print(aggregation)

打印:

[104301 rows x 1 columns]  
      value  
0       NaN  
1       NaN  
...     ...  

这不是我所期望的:/

提前致谢!

更新 EdChum 的评论

data.info():

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 106661 entries, 2016-08-09 13:06:13 to 2016-08-10 13:06:13
Data columns (total 1 columns):
value    106661 non-null float64
dtypes: float64(1)
memory usage: 1.6 MB

【问题讨论】:

  • value 列的dtype 是什么?你能发布data.info()的输出吗?
  • data.resample('1min').mean() 显示什么?这里的问题可能是您分配给一个索引不兼容的空df,这就是为什么您的日期时间索引没有被复制,因为最初索引是int64Index,例如您可以这样做aggregation = pandas.DataFrame({'value':data.resample('1min').mean()})
  • 是的,你完全正确!!谢谢!这是对空df的分配。 print(data.resample('1min').mean() 完美运行。
  • OK 将发布答案

标签: python pandas numpy


【解决方案1】:

这里的问题是您正在尝试添加一个包含索引不兼容的数据的新列,当您创建一个空 df 时,索引类型最初将为 object dtype,您正在添加索引所在的数据datetimeIndex 所以你得到所有行的NaN

如果您在 df 的 ctor 中传递数据和索引,那么这将起作用:

In [9]:
resampled = df.resample('1min').mean()
empty_df = pd.DataFrame({'value':resampled}, index = resampled.index)
empty_df

Out[9]:
                       value
timestamp                   
2016-08-09 11:55:00  1779.87

如果你想要一个 int 索引,那么你可以这样做:

In [17]:
resampled = df.resample('1min').mean()
empty_df = pd.DataFrame()
empty_df['value'] = pd.Series(resampled, index=np.arange(len(resampled.index)))
empty_df

Out[17]:
     value
0  1779.87

【讨论】:

    猜你喜欢
    • 2020-07-20
    • 2017-01-14
    • 2016-01-26
    • 2019-02-25
    • 1970-01-01
    • 2021-12-14
    • 2019-04-15
    • 2017-09-19
    • 1970-01-01
    相关资源
    最近更新 更多