将Panda数据帧转换为此形状

时间:2015-07-08 13:09:20

标签: python pandas

我有像这样的pandas数据框

In [98]: myDict
Out[98]:
{'2015-08-07': [{'redoPerSec': 300}, {'Transactions': 100}, {'IOPS': 400}],
 '2015-08-06': [{'redoPerSec': 300}, {'Transactions': 100}, {'IOPS': 400}]}

In [99]: df = pandas.DataFrame(myDict)

In [100]: df
Out[100]:
              2015-08-06             2015-08-07
0    {'redoPerSec': 300}    {'redoPerSec': 300}
1  {'Transactions': 100}  {'Transactions': 100}
2          {'IOPS': 400}          {'IOPS': 400}

我想将此转换为

以下的内容
Date            redoPerSec          Transactions    IOPS
2015-08-06          300                 100         400
2015-08-07          300                 100         400

1 个答案:

答案 0 :(得分:1)

import pandas as pd

df = pd.DataFrame()
df['2015-08-06'] = [{'redoPerSec': 300}, {'Transactions': 100}, {'IOPS': 400}]
df['2015-08-07'] = [{'redoPerSec': 300}, {'Transactions': 100}, {'IOPS': 400}]

df = df.T

for i in range(3):
    df = df.join(df[i].apply(Series)).drop(i, 1)

df.index.name = 'Date'
print df

输出:

            redoPerSec  Transactions  IOPS
Date                                      
2015-08-06         300           100   400
2015-08-07         300           100   400

修改

自从DataFrame创建dict后,您可以直接使用

df = pd.DataFrame.from_dict(myDict, 'index')

而不是创建DataFrame,然后通过df = df.T转置它。

更多元素解决方案是首先转换dict,使得值为dict而不是list dict,尽管嵌套字典理解更难了解。之后,我们可以按预期直接构建DataFrame

import pandas as pd

myDict = {'2015-08-07': [{'redoPerSec': 300}, {'Transactions': 100}, {'IOPS': 400}],
 '2015-08-06': [{'redoPerSec': 300}, {'Transactions': 100}, {'IOPS': 400}]}

myDict = { k0: { k: v for d in v0 for (k, v) in d.items() } for (k0, v0) in myDict.items()}
df = pd.DataFrame.from_dict(myDict, 'index')