python - 向 pandas MultiIndex 添加一个新分支
问题描述
我有一个数据框,其列是具有级别的多索引
[['a','b'],['one','two']]
我有另一个数据框,其列是具有级别的多索引
[['c'],['one','two']]
我想以自然的方式合并这些多索引以使其具有级别
[['a','b','c'], ['one', 'two']]
我已经尝试了大概 100 件事情,从连接到合并,到 set_names,到 set_index,到 concats 和重命名级别以及提供键、名称和标签,但我不知道我做错了什么。这似乎是一件很自然的事情。我知道必须有一个简单的方法来做到这一点。我基本上是在索引树中添加一个分支。
解决方案
这实际上只是一个连接。
In [14]: arrays = [['bar', 'bar', 'baz', 'baz'],['one', 'two', 'one', 'two']]
In [15]: tuples = list(zip(*arrays))
In [16]: index1 = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
In [17]: arrays = [['foo', 'foo', 'qux', 'qux'],['one', 'two', 'one', 'two']]
In [18]: tuples = list(zip(*arrays))
In [19]: index2 = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
In [21]: df1 = pd.DataFrame(np.random.randn(4,4), columns=index1)
In [23]: df2 = pd.DataFrame(np.random.randn(4,4), columns=index2)
In [25]: pd.concat([df1, df2], axis=1)
Out[25]:
first bar baz foo qux \
second one two one two one two one
0 0.192217 -1.392671 1.229953 0.558334 -0.908125 0.934284 -1.240591
1 0.816492 -0.157933 0.058365 -1.115411 -0.488677 0.204860 -0.268372
2 -0.160077 -1.825912 0.615397 0.570057 -0.699260 -0.552970 0.056875
3 1.308078 0.018694 1.047227 1.047585 0.172404 0.861871 0.569599
first
second two
0 -2.234618
1 -1.604534
2 0.151859
3 0.522803
推荐阅读
- rabbitmq - RabbitMQ 配置为使用自定义的 epmd 端口,但服务器仍然在默认的 epmd 进程上启动
- python - 当随机数达到0时如何结束循环
- java - 休眠搜索 lucene 消耗数据库连接
- python - 使用 python 在 Azure Functions 中进行路由
- javascript - 将 JSON 数据输出到从 FireBase 数据库中提取的道具中
- r - 使用 dplyr (或其他东西)在 R 中重新编码
- bash - 在 bash 中为第一列中的每个不同值查找第 n 列中的最大值
- python - 检查字符串是否有资格从字符串中提取文本 - 正则表达式
- java - ActiveMQ 队列的活动消费者过多
- r - 使用 sqldf() 操作数据框时的问题