首页 > 解决方案 > 熊猫数据框

问题描述

我有一组数据,这是一个嵌套字典。虽然 columnsab有一个条目,但 columncd和组成e,它们具有任意数量的相同长度的元素。

例如:

N = 5
nested_dict = {
"a": np.random.randn(N),
"b": np.random.randn(N),
"c": [{"d":np.random.randn(i+1), "e":np.random.randn(i+1)} for i in range(N)]
}

如何将其转换为多索引 Pandas Dataframe,使该列c具有子标题de,每个都具有提供的数组的长度?

编辑:请参阅下面所需格式的示例:

示例数据框

另外,我可以像普通数据框一样保存和加载这个数据框吗?

标签: pythonpandasdataframemulti-index

解决方案


尝试类似:

import pandas as pd
import numpy as np

N = 5
nested_dict = {
    "a": np.random.randn(N),
    "b": np.random.randn(N),
    "c": [{"d": np.random.randn(i + 1), "e": np.random.randn(i + 1)} for i in range(N)]
}

df = pd.DataFrame(data=nested_dict)
# Normalize Nested Dict and merge back
# Set index to 'a', 'b' and unpack lists
df = df.drop(columns=['c']) \
    .merge(pd.json_normalize(df['c']),
           left_index=True,
           right_index=True) \
    .set_index(['a', 'b']) \
    .apply(lambda x: x.apply(pd.Series).stack())

# Add MultiIndex C back
df.columns = pd.MultiIndex.from_product([['c'], df.columns])

# For Display
print(df.to_string())

输出:

                              C          
                              德
抗体                              
-0.913707 1.015265 0 0.630905 -0.508003
 0.467421 1.880421 0 0.886313 0.026921
                    1 -0.720613 1.027585
-0.314128 -0.756686 0 0.317922 -0.431624
                    1 -1.154708 -0.370363
                    2 0.400752 -0.000786
 0.488310 -0.230924 0 1.303703 -1.414924
                    1 0.242020 1.401058
                    2 -0.369507 0.648304
                    3 1.491819 1.010083
 1.248220 -0.351634 0 0.106272 0.518489
                    1 -1.916420 -0.068814
                    2 -0.090406 -0.237604
                    3 -0.208762 0.163396
                    4 0.664643 -1.272215

推荐阅读