【问题标题】:Grouping and exporting excel rows using python使用python对excel行进行分组和导出
【发布时间】:2020-02-23 07:13:42
【问题描述】:

这是使用 Python。

我有一张 Excel 表格,其最基本的形式如下所示

New York    Cup a   3
Stockholm   Plate b 5
Madrid  Cup a   2
New York    Cup b   5
New York    Plate a 8
Madrid  Cup b   9
Stockholm   Plate a 2
Stockholm   Cup a   5
Stockholm   Cup b   3
Madrid  Cup a   5
New York    Plate a 8

我想将位置分组在一起,以便所有纽约和马德里等都在一起,并将它们导出到单独的 Excel 表中,称为纽约、马德里、斯德哥尔摩。在行上具有相同的信息。所以基本上只是将行复制并粘贴到以该行命名的新 Excel 表中。然后我想在每个杯子的第二页上将所有杯子加在一起,将所有盘子加在一起。在导出数据之前这样做有意义吗?

最终结果 3 个命名为 Excel 工作表,仅包含它们的数据,以及第二张工作表上的一些简单数学运算。

真正的 excel 表处理 15000 行 50 个位置和 100 个项目。因此,这些变化必须是一种程序方式。下一次纽约可能是多伦多。

到目前为止,我已经能够按熊猫对它们进行分组,但之后的每次尝试都失败了。

熊猫新手,所以我认为这个相对容易做。

import pandas as pd

stock_report_excel = "small_stores_blocked_stock_value.xlsx"

df_soh = pd.read_excel(stock_report_excel, sheet_name='SOH')
df_stores = df_soh.groupby(['Site Name'])

猜测循环添加到工作表

将项目添加到工作表 2

导出

【问题讨论】:

    标签: python excel pandas


    【解决方案1】:

    虽然不是很清楚你想要的目的是什么,但我想Pandas MultiIndex DataFrame 可能对你有帮助。我在下面写了一些简单的代码,希望可以进一步指导您。

    import pandas as pd
    sites=pd.Series(['New York','Stockholm','Madrid','New York','New York','Madrid','Stockholm','Stockholm','Stockholm','Madrid','New York'])
    col2=pd.Series(['Cup','Plate','Cup','Cup','Plate','Cup','Plate','Cup','Cup','Cup','Plate'])
    col3=pd.Series(['a','b','a','b','a','b','a','a','b','a','a'])
    col4=pd.Series([3,5,2,5,8,9,2,5,3,5,8])
    data=pd.DataFrame({'sites':sites,'col2':col2,'col3':col3,'col4':col4})
    # You can of course replce all the codes above with Pandas read related functions.
    data1 = data.set_index(['sites','col2','col3']) # Set as MultiIndex DataFrame.
    data1.loc[('New York'),:] # This will give you all the 'New York' data
    data1.loc[('New York','Cup'),:] # This will give you all the 'New York' & 'Cup' data.
    # Retrieving all the 'Cup' data is a bit tricky, see the following
    idx=pd.IndexSlice
    data1.loc[idx[:,'Cup'],:]
    

    输出如下。

    # data
            sites   col2 col3  col4
    0    New York    Cup    a     3
    1   Stockholm  Plate    b     5
    2      Madrid    Cup    a     2
    3    New York    Cup    b     5
    4    New York  Plate    a     8
    5      Madrid    Cup    b     9
    6   Stockholm  Plate    a     2
    7   Stockholm    Cup    a     5
    8   Stockholm    Cup    b     3
    9      Madrid    Cup    a     5
    10   New York  Plate    a     8
    # data1
                          col4
    sites     col2  col3
    New York  Cup   a        3
    Stockholm Plate b        5
    Madrid    Cup   a        2
    New York  Cup   b        5
              Plate a        8
    Madrid    Cup   b        9
    Stockholm Plate a        2
              Cup   a        5
                    b        3
    Madrid    Cup   a        5
    New York  Plate a        8
    # data1.loc[('New York'),:]
                col4
    col2  col3
    Cup   a        3
          b        5
    Plate a        8
          a        8
    # data1.loc[('New York','Cup'),:]
          col4
    col3
    a        3
    b        5
    # data1.loc[idx[:,'Cup'],:]
                         col4
    sites     col2 col3
    New York  Cup  a        3
    Madrid    Cup  a        2
    New York  Cup  b        5
    Madrid    Cup  b        9
    Stockholm Cup  a        5
                   b        3
    Madrid    Cup  a        5
    

    如果您不想看到任何警告并希望保持高性能,您可以使用idx 和显式编码,它们是:

    data1.loc[idx['New York',:,:],:]
    data1.loc[idx['New York','Cup',:],:]
    data1.loc[idx['','Cup',:],:]
    

    下一步是将这些数据选择写入单独的工作表。我对此不是很熟悉,因为我总是将数据写入文本文件。例如,将其中一个写入 csv 文件就像data1.loc[idx['New York','Cup',:],:].to_csv('result.csv',index=False) 一样简单。我建议您搜索所需的功能。 希望这会有所帮助。祝你好运!

    【讨论】:

    • 您好,感谢您的回复。抱歉,如果不清楚。因此,最终目标是让提到的每一行网站成为自己的 Excel 表格。 New York 'Cup a' 3 New York 'Cup b' 5 New York 'Plate a' 8 New York 'Plate a' 8 将此数据放入一个名为 new york 的新 Excel 表中。在数据表的第 2 页上添加所有杯子,无论 a 或 b,因此第 2 页纽约“杯总数”8 纽约“盘子总数”16 每个位置都相同,因此马德里等地相同。目前它正在从工作表中复制和粘贴。但我想自动化这个过程
    • 根据您在此处进一步提供的信息,我相信 Pandas MultiIndex Selection 可能会满足您的要求。我现在正在更改我之前在上面提供的代码,希望它可以进一步指导您。
    【解决方案2】:

    问题的答案

    import pandas as pd
    
    import os
    
    file = "yourfile.xlsx"
    
    extension = os.path.splitext(file)[1]
    
    filename = os.path.splitext(file)[0]
    
    abpath = os.path.dirname(os.path.abspath(file))
    
    df=pd.read_excel(file, sheet_name="sheetname")
    
    colpick = "column to extract" 
    
    cols=list(set(df[colpick].values))
    
    
    def sendtofile(cols):
    
        for i in cols:
            df[df[colpick] == i].to_excel("{}/exported/{}.xlsx".format(abpath, i), sheet_name=i, index=False)
    return
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      • 2018-12-31
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多