python - 熊猫数据框
问题描述
我有一组数据,这是一个嵌套字典。虽然 columnsa
和b
有一个条目,但 columnc
由d
和组成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
具有子标题d
和e
,每个都具有提供的数组的长度?
编辑:请参阅下面所需格式的示例:
另外,我可以像普通数据框一样保存和加载这个数据框吗?
解决方案
尝试类似:
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
推荐阅读
- javascript - 在 Chrome 扩展中添加多个事件监听器
- pyspark - 使用 GradientBoostingClassifier 时出现数据框错误
- c - 在初始化指向结构的指针时选择要使用的正确模式
- c# - 如何将数据库表上的行 ID 转换为枚举?
- c# - Web 请求 - 底层连接已关闭:连接意外关闭
- c++ - 如何使用 std::result_of 获取函数的返回类型?
- node.js - 如何使用 documentClient 在 dynamodb 中按创建日期排序 asc
- r - R 语言:流式传输到 URL
- reactjs - 如何使用 id(键)从 API 呈现数据以确定填充的内容?
- amazon-web-services - 将 Go 项目部署到 AWS Lambda 时出现“PathError”