簡體   English   中英

使用Pandas和numpy插值數據幀時數據發生變化

[英]Data changes while interpolating data frame using Pandas and numpy

我正在嘗試根據小時溫度值計算度數小時。 我正在使用的數據缺少一些日期,因此我試圖對這些數據進行插值。 以下是部分數據;

2012-06-27 19:00:00 24
2012-06-27 20:00:00 23
2012-06-27 21:00:00 23
2012-06-27 22:00:00 16
2012-06-27 23:00:00 15
2012-06-29 00:00:00 15
2012-06-29 01:00:00 16
2012-06-29 02:00:00 16
2012-06-29 03:00:00 16
2012-06-29 04:00:00 17
2012-06-29 05:00:00 17
2012-06-29 06:00:00 18
....
2014-12-14 20:00:00 1
2014-12-14 21:00:00 0
2014-12-14 22:00:00 -1
2014-12-14 23:00:00 8

完整的代碼是;

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
filename = 'Temperature12.xls'
df_temp = pd.read_excel(filename)
df_temp = df_temp.set_index('datetime')
ts_temp = df_temp['temp']
def inter_lin_nan(ts_temp, rule):
    ts_temp = ts_temp.resample(rule)
    mask = np.isnan(ts_temp)
    # interpolling missing values
    ts_temp[mask] = np.interp(np.flatnonzero(mask), np.flatnonzero(~mask),ts_temp[~mask])
    return(ts_temp)
ts_temp = inter_lin_nan(ts_temp,'1H')
print ts_temp['2014-06-28':'2014-06-29']
def HDH (Tcurr,Tref=15.0):
    if Tref >= Tcurr:
        return ((Tref-Tcurr)/24)
    else:
        return (0)
df_temp['H-Degreehours'] = df_temp.apply(lambda row: HDH(row['temp']),axis=1)
df_temp['CDD-CUMSUM'] = df_temp['C-Degreehours'].cumsum()
df_temp['HDD-CUMSUM'] = df_temp['H-Degreehours'].cumsum()
df_temp1=df_temp['H-Degreehours'].resample('H', how=sum)
print df_temp1

現在我有兩個問題; 使用inter_lin_nan函數時,它會插值數據,但它也會更改第二天的數據,而下一個數據與excel文件中提供的數據完全不同。 這很常見還是我錯過了什么? 第二個問題:在代碼末尾,我試圖添加小時度日值,這就是為什么我創建了另一個數據框,但是當我打印該數據框時,它仍然具有原始數據文件中的NaN號。 你能告訴我為什么會這樣嗎? 由於我是Python的新手,我可能會遺漏一些非常明顯的東西。

當熊貓有自己的版本時,請不要使用numpy。

df = pd.read_csv(filepath)
df  =df.asfreq('1d') #get a timeseries with index timestamps each day.
df['somelabel'] = df['somelabel'].interpolate(method='linear') # interpolate nan values

用作頻率以將所需的時間戳頻率添加到時間序列,並使用interpolate()僅插值nan值。

http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.Series.interpolate.html

http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.asfreq.html

暫無
暫無

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

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