Python - 获取一个数据帧,其中时间为索引,多个日期为列

时间:2015-01-06 07:23:14

标签: python pandas melt

我想我需要一些“融化”功能的帮助。

我有一个如下所示的数据框:

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?
  3. 非常感谢你。

1 个答案:

答案 0 :(得分:2)

您可能正在寻找pivot_table,这与melt的倒数相似。为简单起见,以下代码使用" Uhrzeit"重新创建输入DataFrame。包含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.
相关问题