首页 > 解决方案 > 使用 Cyclus 将 Pandas 中的数据排序到工作表中 - 一张表中的多个数据

问题描述

我正在编写一个脚本,它应该能够从 excel 中对大量 od 数据进行排序并进行一些统计,并且在排序部分需要帮助......
我有一个带有多张工作表的大型 excel,每张都有产品列表及其属性并且需要对数据进行排序,以便每个产品都在一张表中。我能做到的。然而,有些产品有不同的名称,尽管它们是相同的,我需要它们都在同一张表中以获得正确的统计数据。

根据下面的代码示例,我有名为 text1、text2、text3、...、text7 的产品。重复是 text2 = text3,text5 = text6。

我已经拥有的是带有
text1、text2、text3、text4、text5、text6、text7的排序数据的表格,
名为
'text1'、'text2'、'text3'、'text4'、'text5'

我需要的是带有
text1、text2+text3、text4、text5+text6、text7的数据表,
名为
'text1'、'text2'、'text4'、'text5'、'text7'

我很抱歉解释不好,希望这说得通。

我什至做了 source-data.xls 的例子,并在这里上传: https ://www.dropbox.com/sh/aiqysx3gyxeuot9/AAAV6mqvvbw5TUIBvzuKCigka?dl=0

有没有可能,或者我应该改变思考问题的方式?

texts_to_find = ['text1', 'text2', 'text4', 'text5', 'text7']
sheets = ['a', 'b', 'c', 'd']

file = 'source-data.xls'
df = []
for sheetName in sheets:
    data = pd.read_excel(file, sheet_name ='{name}'.format(name=sheetName), usecols='B:P', skiprows=1)
    df.append(data)
df = pd.concat(df)

file_out_selected = 'selected-data.xlsx'
with pd.ExcelWriter(file_out_selected) as writer:
    for text in texts_to_find:
        df2 = df[df['column-name'] == text]
        df2.to_excel(writer, header=True, index=False, sheet_name ='{name}'.format(name=text))

标签: pythonexcelpandassorting

解决方案


您必须告诉 Python 必须在同一张表中包含多个名称。一种简单的方法是设置关系 1-N(列表列表)sheet_name -> column_names。

代码可以变成:

texts_to_find = (('text1', ['text1']),
                 ('text2', ['text2', 'text3']),
                 ('text4', ['text4']),
                 ('text5', ['text5', 'text6']),
                 ('text7', ['text7']))

...

file_out_selected = 'selected-data.xlsx'
with pd.ExcelWriter(file_out_selected) as writer:
    for text, texts in texts_to_find:
        df2 = df[df['column-name'].isin(texts)]
        df2.to_excel(writer, header=True, index=False, sheet_name=text)

推荐阅读