【问题标题】:Why does Pandas inner join give ValueError: len(left_on) must equal the number of levels in the index of "right"?为什么 Pandas 内连接会给出 ValueError: len(left_on) must equal the number of levels in index in the index of "right"?
【发布时间】:2015-03-29 12:13:11
【问题描述】:

我正在尝试将 DataFrame A 内部连接到 DataFrame B 并遇到错误。

这是我的加入声明:

merged = DataFrameA.join(DataFrameB, on=['Code','Date'])

这是错误:

ValueError: len(left_on) must equal the number of levels in the index of "right"

我不确定列顺序是否重要(它们并不是真正“有序”的吗?),但以防万一,DataFrame 的组织方式如下:

DataFrameA:  Code, Date, ColA, ColB, ColC, ..., ColG, ColH (shape: 80514, 8 - no index)
DataFrameB:  Date, Code, Col1, Col2, Col3, ..., Col15, Col16 (shape: 859, 16 - no index)

我需要更正我的加入声明吗?还是有另一种更好的方法来获取这两个 DataFrame 的交集(或内部连接)?

【问题讨论】:

  • 需要指出的是,从技术上讲,所有 dfs 和系列和面板都会有一个索引,它可能不是你设置的,但总有一个,可能是从 0 开始的 int64。
  • 完全正确。我只是不知道如何简洁地说出来。标准指数?默认索引?

标签: python pandas join merge inner-join


【解决方案1】:

如果您没有加入索引,请使用merge

merged = pd.merge(DataFrameA,DataFrameB, on=['Code','Date'])

跟进以下问题:

这是一个可重现的例子:

import pandas as pd
# create some timestamps for date column
i = pd.to_datetime(pd.date_range('20140601',periods=2))

#create two dataframes to merge
df = pd.DataFrame({'code': ['ABC','EFG'], 'date':i,'col1': [10,100]})
df2 = pd.DataFrame({'code': ['ABC','EFG'], 'date':i,'col2': [10,200]})

#merge on columns (default join is inner)
pd.merge(df, df2, on =['code','date'])

这个结果是:

    code    col1    date    col2
0   ABC     10      2014-06-01  10
1   EFG     100     2014-06-02  200

运行此代码时会发生什么?

【讨论】:

  • merge 甚至还有一个连接类型的参数,如何:{'left', 'right', 'outer', 'inner'}, default 'inner'
【解决方案2】:

这是执行join 的另一种方式。与已验证的答案不同,这是一个更普遍的答案,适用于所有其他类型的联接

内连接

inner join也可以通过在how中明确提及如下来执行:

pd.merge(df1, df2, on='filename', how='inner')

同样的方法适用于其他类型的连接:

外连接

pd.merge(df1, df2, on='filename', how='outer')

左加入

pd.merge(df1, df2, on='filename', how='left')

右加入

pd.merge(df1, df2, on='filename', how='right')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-16
    • 2022-12-19
    • 2020-07-03
    • 2022-11-05
    • 2023-02-09
    • 2022-12-01
    • 1970-01-01
    • 2013-09-30
    相关资源
    最近更新 更多