【问题标题】:Pandas combine multiple excel worksheets on specific index熊猫在特定索引上组合多个 excel 工作表
【发布时间】:2015-12-24 15:50:33
【问题描述】:

我有一个包含多个工作表的 excel 文件。每个工作表都包含特定月份的各个项目代码的价格和库存数据。

例如...

工作表名称 = 201509

code price inventory 
5001  5       92
5002  7       50
5003  6       65

工作表名称 = 201508

code price inventory
5001  8       60
5002  10      51
5003  6       61

使用 pandas 数据框,导入此数据的最佳方式是什么,按时间和项目代码组织。 例如,我需要这个数据框最终能够绘制项目代码 5001 的价格和库存变化。

感谢您的帮助。我还是 python/pandas 的新手。 谢谢。


我的解决方案... 这是我找到的解决问题的方法。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

D201509 = pd.read_excel('ExampleSpreadsheet.xlsx', sheetname='201509', index_col='Code')
D201508 = pd.read_excel('ExampleSpreadsheet.xlsx', sheetname='201508', index_col='Code')
D201507 = pd.read_excel('ExampleSpreadsheet.xlsx', sheetname='201507', index_col='Code')
D201506 = pd.read_excel('ExampleSpreadsheet.xlsx', sheetname='201506', index_col='Code')
D201505 = pd.read_excel('ExampleSpreadsheet.xlsx', sheetname='201505', index_col='Code')

total = pd.concat(dict(D201509=D201509, D201508=D201508, D201507=D201507, D201506=D201506, D201505=D201505), axis=1)

total.head()

这将很好地生成带有分层列的数据框..

现在我的新问题是,您将如何使用此数据框绘制每个代码 # 的价格变化? 我想查看 5 行(5001,5002,5003,5004,5005),x 轴是时间(D201505、D201506 等),y 轴是价格值。

谢谢。

【问题讨论】:

    标签: python excel pandas


    【解决方案1】:

    这会将您的数据放入数据框中并在 5001 上绘制散点图

    import pandas as pd
    import matplotlib.pyplot as plt
    import xlrd
    
    file = r'C:\dickster\data.xlsx'
    list_dfs = []
    
    xls = xlrd.open_workbook(file, on_demand=True)
    for sheet_name in xls.sheet_names():
        df = pd.read_excel(file,sheet_name)
        df['time'] = sheet_name
        list_dfs.append(df)
    
    dfs = pd.concat(list_dfs,axis=0)
    dfs = dfs.sort(['time','code'])
    

    看起来像:

       code  price  inventory    time
    0  5001      8         60  201508
    1  5002     10         51  201508
    2  5003      6         61  201508
    0  5001      5         92  201509
    1  5002      7         50  201509
    2  5003      6         65  201509
    

    现在是 5001 的情节:价格 v 库存:

    dfs[dfs['code']==5001].plot(x='price',y='inventory',kind='scatter')
    plt.show()
    

    产生:

    【讨论】:

    • 我喜欢这个解决方案,你能看到我对这个原始问题所做的编辑并帮助我绘制新数据框的图形吗?
    • 我认为最好开始一个新问题,因为我们已经从合并 excel 工作表转向与 matplotlib 中的多系列绘图更相关的问题。我已经准备好一个示例实现。
    猜你喜欢
    • 2018-06-13
    • 2021-10-03
    • 1970-01-01
    • 2020-11-09
    • 2016-10-16
    • 2019-01-19
    • 2016-10-22
    • 2021-09-01
    • 2018-02-03
    相关资源
    最近更新 更多