将pandas多索引数据框转换为具有所有索引列的简单数据框

时间:2019-10-20 09:23:45

标签: pandas

为图片表示歉意,但是由于获得了这些数据,我不确定如何重现此内容...

Multi index dataframe

我只是想将其转换为一个简单的数据框,其中有索引列timelonlat以及各个行中的值,如下所示:

| time | lat | lon | data |

我尝试做.reset_index(),但是time轴仍然跨过而不是向下。如何“分解”所有索引值以获得一个包含所有索引列的简单数据框?

编辑:

用于再现的测试数据字典:

{Timestamp('2001-01-01 00:00:00'): {(50.18000030517578,
   -5.6199951171875): -1.68,
  (50.18000030517578, -4.9200439453125): -1.88,
  (50.18000030517578, -4.219970703125): -2.08},
 Timestamp('2001-01-02 00:00:00'): {(50.18000030517578,
   -5.6199951171875): -1.95,
  (50.18000030517578, -4.9200439453125): -2.25,
  (50.18000030517578, -4.219970703125): -2.55},
 Timestamp('2001-01-03 00:00:00'): {(50.18000030517578,
   -5.6199951171875): -0.76,
  (50.18000030517578, -4.9200439453125): -0.91,
  (50.18000030517578, -4.219970703125): -1.06},
 Timestamp('2001-01-04 00:00:00'): {(50.18000030517578,
   -5.6199951171875): -2.9,
  (50.18000030517578, -4.9200439453125): -3.01,
  (50.18000030517578, -4.219970703125): -3.11},
 Timestamp('2001-01-05 00:00:00'): {(50.18000030517578,
   -5.6199951171875): -2.06,
  (50.18000030517578, -4.9200439453125): -2.29,
  (50.18000030517578, -4.219970703125): -2.52}}

1 个答案:

答案 0 :(得分:3)

检查:

import pandas as pd
from pandas import Timestamp


d = {Timestamp('2001-01-01 00:00:00'): {(50.18000030517578,
   -5.6199951171875): -1.68,
  (50.18000030517578, -4.9200439453125): -1.88,
  (50.18000030517578, -4.219970703125): -2.08},
 Timestamp('2001-01-02 00:00:00'): {(50.18000030517578,
   -5.6199951171875): -1.95,
  (50.18000030517578, -4.9200439453125): -2.25,
  (50.18000030517578, -4.219970703125): -2.55},
 Timestamp('2001-01-03 00:00:00'): {(50.18000030517578,
   -5.6199951171875): -0.76,
  (50.18000030517578, -4.9200439453125): -0.91,
  (50.18000030517578, -4.219970703125): -1.06},
 Timestamp('2001-01-04 00:00:00'): {(50.18000030517578,
   -5.6199951171875): -2.9,
  (50.18000030517578, -4.9200439453125): -3.01,
  (50.18000030517578, -4.219970703125): -3.11},
 Timestamp('2001-01-05 00:00:00'): {(50.18000030517578,
   -5.6199951171875): -2.06,
  (50.18000030517578, -4.9200439453125): -2.29,
  (50.18000030517578, -4.219970703125): -2.52}}


df = pd.DataFrame(d)
df = df.stack().to_frame().reset_index()
df.columns = ['lat', 'lon', 'time', 'data']

输出:

      lat       lon       time  data
0   50.18 -5.619995 2001-01-01 -1.68
1   50.18 -5.619995 2001-01-02 -1.95
2   50.18 -5.619995 2001-01-03 -0.76
3   50.18 -5.619995 2001-01-04 -2.90
4   50.18 -5.619995 2001-01-05 -2.06
5   50.18 -4.920044 2001-01-01 -1.88
6   50.18 -4.920044 2001-01-02 -2.25
7   50.18 -4.920044 2001-01-03 -0.91
8   50.18 -4.920044 2001-01-04 -3.01
9   50.18 -4.920044 2001-01-05 -2.29
10  50.18 -4.219971 2001-01-01 -2.08
11  50.18 -4.219971 2001-01-02 -2.55
12  50.18 -4.219971 2001-01-03 -1.06
13  50.18 -4.219971 2001-01-04 -3.11
14  50.18 -4.219971 2001-01-05 -2.52