python - 加入数据框——一个有多索引列,另一个没有

标签 python pandas join multi-index

我正在尝试连接两个数据框 - 一个具有多索引列,另一个具有单个列名称。它们具有相似的指数。

我收到以下警告:

"UserWarning: merging between different levels can give an unintended result (3 levels on the left, 1 on the right)"

例如:

import pandas as pd
import numpy as np

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
          ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])

np.random.seed(2022)  # so the data is the same each time
df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)
df2 = pd.DataFrame(np.random.randn(3), index=['A', 'B', 'C'],columns=['w'])

df3 = df.join(df2)

DataFrame View

df

first        bar                 baz                 foo                 qux          
second       one       two       one       two       one       two       one       two
A      -0.000528 -0.274901 -0.139286  1.984686  0.282109  0.760809  0.300982  0.540297
B       0.373497  0.377813 -0.090213 -2.305943  1.142760 -1.535654 -0.863752  1.016545
C       1.033964 -0.824492  0.018905 -0.383344 -0.304185  0.997292 -0.127274 -1.475886

df2

          w
A -1.940906
B  0.833649
C -0.567218

df3 - 结果

   (bar, one)  (bar, two)  (baz, one)  (baz, two)  (foo, one)  (foo, two)  (qux, one)  (qux, two)         w
A   -0.000528   -0.274901   -0.139286    1.984686    0.282109    0.760809    0.300982    0.540297 -1.940906
B    0.373497    0.377813   -0.090213   -2.305943    1.142760   -1.535654   -0.863752    1.016545  0.833649
C    1.033964   -0.824492    0.018905   -0.383344   -0.304185    0.997292   -0.127274   -1.475886 -0.567218

  • df.join(df2) 来自 pandas v1.3.0导致 FutureWarning
    • FutureWarning:不同级别之间的合并已弃用,并将在未来版本中删除。 (左侧 2 级,右侧 1 级)df3 = df.join(df2)

加入这两个数据框的最佳方式是什么?

最佳答案

这取决于你想要什么!您希望 df2 中的列与 df 中的第一级或第二级列对齐吗?

你必须在 df2 的列中添加一个级别

pd.concat super 俗气

df.join(pd.concat([df2], axis=1, keys=['a']))

更好的方式

df2.columns = pd.MultiIndex.from_product([['a'], df2.columns])

df.join(df2)

enter image description here

关于python - 加入数据框——一个有多索引列,另一个没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43223615/

相关文章:

python - 根据列值对有序 Pandas 数据框中的行进行分组

python - 如何将 numpy.array 作为新列添加到 pyspark.SQL DataFrame?

python - 将序号日期转换为 dd-mm-YYYY 日期

python - 如何在 Pandas 的所有适用行中复制 groupby 的平均值

python - Pandas 数据帧 : How to merge dataframe with multiple index and single index

php - 当我将 Zend_Db_Table_Abstract 与 select 和 join 一起使用时,fetchAll 返回一行

mysql - 如何在 UPDATE 查询中执行三个表 JOIN?

python - 在 Google App Engine 中使用 ctypes 来使用二进制文件?

Python:一种从 Python 字典中删除空列表的优雅方法

MySQL 创建连接两个完整表的 View