【问题标题】:How to create a list from pandas dataframes如何从熊猫数据框创建列表
【发布时间】:2021-09-29 19:54:37
【问题描述】:

我有一组 excel 文件,我正在尝试循环创建一系列 pandas 数据框(如下所示)。每个数据帧命名为 1001、1002、1003 等。

store_1001 = pd.DataFrame(pd.read_excel(1001.xls))
Print(store_1001)

    0    Apples Oranges Grapes Mango Total  
    9      15     16      1     0     32

store_1002 = pd.DataFrame(pd.read_excel(1002.xls))
Print(store_1002)

    0    Apples Oranges Grapes Mango Total  
    9      35     8      21     28     92

store_1003 = pd.DataFrame(pd.read_excel(1003.xls))
Print(store_1003)

    0    Apples Oranges Grapes Mango Total  
    9      0     0       0      0     0

我想从每个数据框中提取总数来创建列表。我的最终目标是使用旧数据框名称和相应值创建一个新数据框。

0 Store Items
1 1001   32 
2 1002   92 
3 1003   0

到目前为止,我可以制作此表的第一列,但我一直坚持一次从一个表中提取索引(不知道如何循环)。任何帮助将不胜感激!

【问题讨论】:

  • 如果没有示例数据很难具体回答,但一种方法可能是将 assign 存储 ID 到每个数据帧,加入并与 groupbypivot_table 进行汇总。
  • 我添加了一些额外的数据,希望能让问题更清楚。

标签: python pandas dataframe loops


【解决方案1】:

假设所有 excel 文件都在一个单独的目录中,您可以使用 listdir 模块中的 listdir 方法获取所有 excel 文件的列表。 is 的代码如下所示:

import os
file_list = os.listdir(path)

这里path 是包含所有用于存储数据的excel 文件的目录的路径。获得文件列表后,您可以遍历它并获取/处理每个数据帧的数据。

我在下面为你举了一个小例子。


import os
import pandas as pd

df_list = []
df_total = []

for file_name in os.listdir(path):  # path -> path to the directory that contains all the excel files
    # exception handling in case directory has non-excel files
    try:
        df = pd.read_excel(file_name)
    except:
        continue
    # get the df total here (I'm assuming your dataframe has a single row as per the example)
    total = df.iloc[0]['total']

    # adding file name to df_list
    df_list.append(os.path.splitext(file_name)[0])  # removes extension, keeping just file name 

    # adding df total to df_total list
    df_total.append(total)

# creating the final dataframe with total from each mini-dataframe
total_df = pd.DataFrame({
    "store": df_list,
    "items": df_total,
})

【讨论】:

    【解决方案2】:

    假设每个 Excel 文件都以商店编号命名:

    df = pd.concat(pd.read_excel(f'{n}.xls').assign(store=n)
                   for n in [1001,1002,1003], axis=0)
    
    # using sample data
    df1 = pd.DataFrame({'0': {0: 9}, 'Apples': {0: 15}, 'Oranges': {0: 16}, 'Grapes': {0: 1}, 'Mango': {0: 0}, 'Total': {0: 32}})
    df2 = pd.DataFrame({'0': {0: 9}, 'Apples': {0: 35}, 'Oranges': {0: 8}, 'Grapes': {0: 21}, 'Mango': {0: 28}, 'Total': {0: 92}})
    df3 = pd.DataFrame({'0': {0: 9}, 'Apples': {0: 0}, 'Oranges': {0: 0}, 'Grapes': {0: 0}, 'Mango': {0: 0}, 'Total': {0: 0}})
    df = pd.concat([df1.assign(store=1001),
                    df2.assign(store=1002),
                    df3.assign(store=1003)], axis=0)
    
    df.groupby('store')['Total'].sum()
    

    产量

    store
    1001    32
    1002    92
    1003     0
    Name: Total, dtype: int64
    

    根据 Excel 文件的数量,您可以考虑一种自动生成商店 ID/Excel 文件名列表的方法。

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 1970-01-01
      • 2023-01-14
      • 2017-08-27
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 2016-04-21
      相关资源
      最近更新 更多