2015-01-06 30 views
0

我想我需要一些「熔化」功能的幫助。Python - 以時間爲索引,獲得一個數據幀作爲索引和幾個日期列

我有一個數據幀,它看起來像以下:

enter image description here

正如你可以看到當前的指數是時間。

但是,如果想實現以下目標:

enter image description here

背後的理由是,我想比較同季的RZS值不同天。

我知道我可以使用熔體功能,但我不知道這個功能是如何工作的?

from pandas import melt 

df = pd.DataFrame(index=['00:00:00', '00:15:00'], columns=["2014-12-01","2014-12-02"]) 

它創建數據框,但我不知道如何來填補它。 我的問題:

  1. 什麼是最簡單的方法來創建一個包含所有96個季度的一天的索引?
  2. 如何使用融化函數來填充新的df?

非常感謝您提前。

回答

2

您可能在尋找pivot_table,這與melt相反。爲簡單起見,下面的代碼重新創建輸入數據幀與包含「Uhrzeit」列96的整數值,表示時間宿舍:

import pandas as pd 
import numpy as np 

data = { 
    'Datum': ['2014-12-01'] * 96 + ['2014-12-02'] * 96, 
    'Uhrzeit': range(96) + range(96), 
    'RZS': np.random.rand(96*2), 
} 

df = pd.DataFrame(data).set_index('Datum')[['Uhrzeit', 'RZS']] 
df.reset_index(inplace=True) # Now this df looks like the input you described 
df = pd.pivot_table(df, values='RZS', rows='Uhrzeit', cols='Datum') 
print df[:10] 

輸出:

Datum 2014-12-01 2014-12-02 
Uhrzeit       
0   0.864674 0.363400 
1   0.736678 0.925202 
2   0.807088 0.076891 
3   0.007031 0.528020 
4   0.047997 0.216422 
5   0.625339 0.636028 
6   0.115018 0.141142 
7   0.424289 0.101075 
8   0.544412 0.147669 
9   0.151214 0.274959 

可以然後切片出包含數據幀所需的「Uhrzeit」。


編輯:看來列RZS被表示爲字符串,因爲它預期值列是數值導致一些問題pivot_table。這裏是一個快速解決該列轉換爲數值,假設STR '1.087,29'應該算是一個浮動1087.29

df = pd.DataFrame({'RZS': ['1.087,29', '1.087.087,28', '1.087.087.087,28']}) 

def fix(x): 
    return x.replace('.', '').replace(',', '.') 

df['RZS'] = df['RZS'].apply(fix).astype(float) 

# The column RZS now should be of dtype float, and pivot_table should work. 
+0

你好,非常感謝你這一點。但是,我收到以下錯誤:「沒有數字類型進行聚合」。首先,我認爲原因是我有逗號分隔的值,而不是虛線,即1,23而不是1.23。但是,我用「」替換了「,」。並且錯誤仍然存​​在... – Johannes

+0

你能檢查'RZS'(''df.dtypes'')列的dtype嗎?它必須是數字(請參閱此[問題](http://stackoverflow.com/questions/19279229/pandas-pivot-table-with-non-numeric-values-dataerror-no-numeric-types-to-ag) )。 –

+0

好吧,我發現了這個問題。你能告訴我如何將1.087,29(千..)轉換成這個1087.29?我以這種方式嘗試了替換功能:替換「。」按「」和「,」按「」。但比它拋出一個空系列... – Johannes

相關問題