python - 使用 pandas 连接多索引列
问题描述
如何连接两个 pandas 数据帧,其中一个数据帧具有多索引列?我需要在最终数据框中保留多索引。
import numpy as np
import pandas as pd
df1_cols = ["a", "b"]
df1_vals = np.random.randint(1, 10, [2, 2])
df1 = pd.DataFrame(data=df1_vals, columns=df1_cols)
df2_cols = pd.MultiIndex.from_tuples([("c", "1"), ("c", "2"), ("d", "1"), ("d", "2")])
df2_vals = np.random.randint(1, 10, [2, 4])
df2 = pd.DataFrame(data=df2_vals, columns=df2_cols)
df = pd.concat([df1, df2], axis=1)
使用pd.concat()
,多索引将被压缩。
a b (c, 1) (c, 2) (d, 1) (d, 2)
0 3 7 1 6 1 3
1 6 1 2 7 6 3
解决方案
您需要MultiIndex
在两个 DataFrame 中用于MultiIndex
最终 DataFrame:
df1.columns = pd.MultiIndex.from_product([df1.columns, ['']])
print (df1.columns)
MultiIndex([('a', ''),
('b', '')],
)
df = pd.concat([df1, df2], axis=1)
print (df)
a b c d
1 2 1 2
0 5 6 6 9 7 7
1 1 7 7 7 2 6
推荐阅读
- java - 如何在java中的数字和字符之间分割字符串
- python - Splunk 如何在 python SSL 中执行此操作
- c++ - 在 C++ 字符串中,为什么在最后一个字符之后,通过 index 和 at() 访问时行为不同?
- php - 将数组放入数组中
- wordpress - 访问子主题模板页面
- python - 有没有办法使用 Python 合并上传到 AWS S3 存储桶的多个 CSV 文件?
- flutter - 如何在 Flutter 中创建可迭代的对象实例集合?
- python - 我如何在我的程序中完成我的 tkinter?
- sql - 使用窗口函数计算滚动计数
- curl - 为什么我无法使用 curl 获取 Watson-assistant v2 API 的会话 ID?