2017-08-30 87 views
0

我試圖過濾一個pandas DataFrame,並且使用測試用例和真實數據得到了不同的結果。使用真實數據我得到了NaN的值,而在測試案例中,我得到了我期望的結果。按照日期時間索引過濾大熊貓DataFrame的不同結果

測試用例:

測試情況下,我創建了下面的代碼:

import pandas as pd 
df1 = pd.DataFrame([ 
["2014-08-06 12:10:00", 19.85, 299.96, 17.5, 228.5, 19.63, 571.43], 
["2014-08-06 12:20:00", 19.85, 311.55, 17.85, 248.68, 19.78, 547.21], 
["2014-08-06 12:30:00", 20.06, 355.27, 18.35, 224.82, 19.99, 410.68], 
["2014-08-06 12:40:00", 20.14, 405.95, 18.49, 247.33, 20.5, 552.79], 
["2014-08-06 12:50:00", 20.14, 352.87, 18.7, 449.33, 20.86, 616.44], 
["2014-08-06 13:00:00", 20.28, 356.96, 18.92, 307.57, 21.15, 471.18]], 
columns=["date_time","t1", "1", "t4", "4", "t6", "6"]) 
df1 = df1.set_index(["date_time"]) 
df1 = pd.to_datetime(df1) 

filter1 = pd.DataFrame(["2014-08-06 12:20:00","2014-08-06 13:00:00"]) 
df1_filtered = df1.ix[filter1[filter1.columns[0]][0:2]] 

正如你所期待的結果是:

>>> df1_filtered 
         t1  1  t4  4  t6  6 
2014-08-06 12:20:00 19.85 311.55 17.85 248.68 19.78 547.21 
2014-08-06 13:00:00 20.28 356.96 18.92 307.57 21.15 471.18 

使用真實的數據:

Real data來自一個txt文件,看起來像這樣:

Fecha_hora t1 1 t4 4 t6 6 
2014-08-06 12:10:00 19.85 299.96 17.5 228.5 19.63 571.43 
2014-08-06 12:20:00 19.85 311.55 17.85 248.68 19.78 547.21 
2014-08-06 12:30:00 20.06 355.27 18.35 224.82 19.99 410.68 
2014-08-06 12:40:00 20.14 405.95 18.49 247.33 20.5 552.79 
2014-08-06 12:50:00 20.14 352.87 18.7 449.33 20.86 616.44 
2014-08-06 13:00:00 20.28 356.96 18.92 307.57 21.15 471.18 

然而,當我讀到真實的數據,這樣一來之前使用相同的過濾器:

df2 = pd.read_csv(r"D:/tmp/data.txt", sep='\t', parse_dates=True, index_col=0) 
df2_filtered = df2.ix[filter1[filter1.columns[0]][0:2]] 

我獲得以下與值結果NaN

>>> df2_filtered 
        t1 1 t4 4 t6 6 
2014-08-06 12:20:00 NaN NaN NaN NaN NaN NaN 
2014-08-06 13:00:00 NaN NaN NaN NaN NaN NaN 

但我仍然可以從某行這樣得到的數值:

>>> df2.ix["2014-08-06 12:20:00"] 
t1  19.85 
1  311.55 
t4  17.85 
4  248.68 
t6  19.78 
6  547.21 
Name: 2014-08-06 12:20:00 

問:

我如何才能得到同樣的結果在我的測試案例篩選我真實的數據?可能有更好的方法來實現我在找的東西嗎?

注意:我pandas版本python 2.5下使用0.9.0。意思是我沒有loc功能。

注2:我甚至在pythonanywhere.com下使用python 2.7試過,結果相同。但是,如果我檢查df1==df2我得到True爲每個值。

回答

1

希望不言而喻,但如果可能的話,請升級您的python/pandas!

在這種情況下,在最近的版本(0.20.3)中,我在兩種情況下都會缺少值 - 我需要將查找鍵轉換爲日期時間,我猜測它也適用於您。

基於便捷字符串的日期索引只能用於標量/切片。

In [174]: lookup = pd.to_datetime(filter1[filter1.columns[0]][0:2]) 

In [175]: df2.ix[lookup] 
Out[175]: 
         t1  1  t4  4  t6  6 
Fecha_hora              
2014-08-06 12:20:00 19.85 311.55 17.85 248.68 19.78 547.21 
2014-08-06 13:00:00 20.28 356.96 18.92 307.57 21.15 471.18 
+0

太棒了!這解決了我的問題!謝謝!我希望我可以更新我的python/pandas,但是因爲我需要使用從'python 2.5'下編寫的外部程序的API,所以我暫時停留在那裏... –

相關問題