【问题标题】:Create a dataframe of the column with the same name from multiple excel worksheets in Python从Python中的多个excel工作表中创建具有相同名称的列的数据框
【发布时间】:2020-09-15 03:06:56
【问题描述】:

假设我有一个包含 100 张工作表的 excel 文件。在一个玩具示例中,床单被称为 = ['Apple', 'Farm', 'Kitchen', 'Napkin']

工作表有多个列,但它们都有一个名为“销售”的列

我想要一个包含所有 4 种产品的 Sales 的 python 数据框,方法是将工作表的名称附加到单词 Sales 上

看起来像这样:

Apple_Sales    Farm_Sales     Kitchen_Sales     Napkin_Sales

05               52               104               75
66              103               198               09
...              ..               ...               ..

到目前为止,我能够将 excel 工作表导入数据框字典,但这不是我想要的

sales = r'D:/user/...../Sales.xlsx'

sal = pd.ExcelFile(Sales)
dictsdf = {sheets:sal.parse(sheets:sal) for sheets:sal in sal.sheet_names}

【问题讨论】:

    标签: python python-3.x excel


    【解决方案1】:

    请检查代码段。

    涉及的步骤

    1. 将列名称创建为工作表名称+销售额
    2. 读取excel文件并转换为dataframe
    3. 如果 Sales 存在于数据框中,则将值存储在列表中。
    4. 合并 1 和 3 以将工作表名称和销售值的键值对创建为嵌套列表。
    5. 转置嵌套列表并根据索引值转换为数据帧

    我的excel文件是这样的

    import pandas as pd
    datadic = pd.read_excel('data.xlsx', sheet_name=None)
    sheets=datadic.keys()
    sheets=[i+"_"+'Sales' for i in sheets]
    
    dictoframe=pd.Series(datadic).to_frame()
    print(dictoframe.to_markdown())
    
    """
    |         | 0                    |
    |:--------|:---------------------|
    | Apple   | a  b  c  Sales       |
    |         | 0  1  2  3      4    |
    |         | 1  5  6  7      8    |
    | Farm    | d  Sales   e   f     |
    |         | 0   9     10  11  12 |
    |         | 1  13     14  15  16 |
    | Kitchen | Sales   g   h   i    |
    |         | 0     17  18  19  20 |
    |         | 1     21  22  23  24 |
    | Napkin  | j   k  Sales   l     |
    |         | 0  25  26     27  28 |
    |         | 1  29  30     31  32 |
    """
    
    listofsales=[i['Sales'].tolist() for i in dictoframe[0] if('Sales' in i)]        
    finaldic=dict(zip(sheets,listofsales))
    df=pd.DataFrame.from_dict(finaldic,orient='index').transpose()
    print(df)
    
    """
       Apple_Sales  Farm_Sales  Kitchen_Sales  Napkin_Sales
    0            4          10             17            27
    1            8          14             21            31
    """
    

    【讨论】:

      猜你喜欢
      • 2018-02-04
      • 1970-01-01
      • 2017-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多