【问题标题】:shape mismatch: objects cannot be broadcast to a single shape形状不匹配:对象不能广播到单个形状
【发布时间】:2023-02-25 16:15:41
【问题描述】:

我想合并给定文件的工作表,但我的代码给了我给定的类型错误 TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame"

import pandas as pd

wb_url = r'D:\DA\power query data\Excel Power Query Practice Material\36. Power Query - Append                    Queries\Append Queries\Yearly Data - Tables - Quick Method.xlsx'

excel_file = pd.read_excel(wb_url, sheet_name=None)
combined_df = pd.concat(excel_file)

【问题讨论】:

    标签: python-3.x pandas typeerror data-analysis


    【解决方案1】:

    有两个问题:excel_file 是一个将每个工作表名称映射到 DataFrame 的字典,因此我们需要在使用它之前解压缩 excel_file,pd.concat 需要一系列对象(例如 DataFrame 列表)

    使用示例 excel 文件(由三张表组成,其中包含名为 ab 的列),我们可以执行以下操作:

    import pandas as pd
    
    excel_file = pd.read_excel("test.xlsx", sheet_name=None)
    combined_df = pd.DataFrame()
    for sheet_name, sheet_df in excel_file.items():
        combined_df = pd.concat([combined_df, sheet_df])
    

    结果:

    >>> combined_df
         a     b
    0  1.0  10.0
    1  2.0  20.0
    2  3.0  30.0
    0  4.0  40.0
    1  5.0  50.0
    2  6.0  60.0
    0  7.0  70.0
    1  8.0  80.0
    2  9.0  90.0
    

    注意:如果你愿意,你也可以重新设置索引,但是为了这个演示的目的,我希望清楚每个工作表的数据来自哪里

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 2021-05-22
      • 2013-06-01
      • 1970-01-01
      • 2021-01-23
      • 2021-05-13
      • 2021-02-27
      • 1970-01-01
      相关资源
      最近更新 更多