pandas - 列表的数据框到 multiIndex 数据框
问题描述
我有一个列表数据框,列表中的每个值代表更大数据集的平均值、标准差和值的数量。我想为该列表中的三个值创建一个子索引。
一个示例数据框是:
np.random.seed(2)
d={i: {j:[np.random.randint(10) for i in range(0,3)] for j in ['x','y','z']} for i in ['a','b','c']}
pd.DataFrame.from_dict(d,orient='index')
这使:
x y z
a [1, 4, 5] [7, 4, 4] [0, 6, 3]
b [7, 1, 9] [1, 3, 8] [3, 6, 2]
c [1, 6, 6] [6, 5, 0] [6, 5, 9]
我想:
x y z
mean std count mean std count mean std count
a 1 4 5 7 4 4 0 6 3
b 7 1 9 1 3 8 3 6 2
c 1 6 6 6 5 0 6 5 9
解决方案
您可以使用numpy concatenate和numpy vstack连接内部列表,构建 MultiIndex 列,然后生成一个新数据框:
np.random.seed(2)
d = {
i: {j: [np.random.randint(10) for i in range(0, 3)] for j in ["x", "y", "z"]}
for i in ["a", "b", "c"]
}
df = pd.DataFrame.from_dict(d, orient="index")
df
x y z
a [8, 8, 6] [2, 8, 7] [2, 1, 5]
b [4, 4, 5] [7, 3, 6] [4, 3, 7]
c [6, 1, 3] [5, 8, 4] [6, 3, 9]
data = np.vstack([np.concatenate(entry) for entry in df.to_numpy()])
columns = pd.MultiIndex.from_product([df.columns, ["mean", "std", "count"]])
pd.DataFrame(data, columns=columns, index = df.index)
x y z
mean std count mean std count mean std count
a 8 8 6 2 8 7 2 1 5
b 4 4 5 7 3 6 4 3 7
c 6 1 3 5 8 4 6 3 9
更新:2021 年 10 月 5 日
另一种选择是将初始数据帧转换为字典并与 pd.concat 连接:
outcome = {k:pd.DataFrame([*v],
columns = ['mean', 'std', 'count'],
index = v.index)
for k,v in df.items()}
pd.concat(outcome, axis = 1)
x y z
mean std count mean std count mean std count
a 8 8 6 2 8 7 2 1 5
b 4 4 5 7 3 6 4 3 7
c 6 1 3 5 8 4 6 3 9
推荐阅读
- git - 重命名或移动 Git 存储库中的项目模块并保留历史记录
- java - 使用 JSTL 遍历地图
- angularjs - Angular ng-click 未重定向到控制器模板 URL
- apache-nifi - GetFile/ListFile/FetchFile 可以配置为每个触发器重复列表吗?
- python - 如何为 Python 类而不是其实例定义运算符
- ios - ld: 找不到 -lRCTBlob 的库
- javascript - 计算属性中的`property.[]`和`property`有什么区别
- django - Django Rest Framework 避免身份验证 JWT
- python - 在 Python 中以正确的方式导入文件/模块
- php - password_verify 在真密码上为假