我正在尝试连接两个数据框 - 一个具有多索引列,另一个具有单个列名称。它们具有相似的指数。
我收到以下警告:
"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)
关于python - 加入数据框——一个有多索引列,另一个没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43223615/