【问题标题】:Transforming multiple dataframes with pandas using a loop使用循环使用 pandas 转换多个数据帧
【发布时间】:2019-08-03 10:15:26
【问题描述】:

我目前正在做一个项目,我必须从一个 Excel 文件中进行一些转换和清理,该文件在每张表中都有相同的表,只是每张表代表不同的月份(表中的值不同)。

因此,将进行转换的代码仅对于不同的工作表是相同的。

df_at_jan  = pd.read_excel("C:/Users/Spiros/Desktop/Reporting.xlsx",
                      sheet_name='Jan 2018')
df_at_feb  = pd.read_excel("C:/Users/Spiros/Desktop/Reporting.xlsx",
                          sheet_name='Feb 2018')

df_at_jan.drop([0,1,2],axis=0)
df_at_jan.columns = df_at_jan.iloc[3]

df_at_feb.drop([0,1,2],axis=0)
df_at_feb.columns = df_at_feb.iloc[3]

当然,我必须在所有月份都这样做,我想知道如何使用 for 循环来做到这一点,以免为每个不同的月份重新创建代码。

我对 Python 非常陌生,因此非常感谢任何帮助。

非常感谢!

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我无法测试,因为你没有给出数据示例,但是根据thisthis的答案,你可以试试:

    xl = pd.ExcelFile('C:/Users/Spiros/Desktop/Reporting.xlsx')
    
    sheets = xl.sheet_names
    
    df_array = []
    
    for sheet in sheets:
      df_temp = pd.read_excel(xl , sheet)
      df_temp = df_temp.drop([0,1,2],axis=0)
      df_temp.columns = df_temp.iloc[3]
    
      df_array.append(df_temp)
    

    每个月的数据都会在数组的某个位置。

    如果您需要将所有数据变成单个 DataFrame,请执行以下操作:

    df = pd.concat(df_array, ignore_index = True)
    

    【讨论】:

      【解决方案2】:

      1) 创建函数

      def read_one_month(sheet_name):
         df = pd.read_excel("C:/Users/Spiros/Desktop/Reporting.xlsx",
                            sheet_name=sheet_name)
         df.drop([0,1,2],axis=0, inplace = True)
         return df
      

      2) 定义工作表名称数组并运行循环:

      df = pd.DataFrame(None)
      for sheet_name in ['Jan 2018','Feb 2018']:
         df = pd.concat([df, read_one_month(sheet_name)], axis = 0, ignore_index = True)
      
      

      【讨论】:

        猜你喜欢
        • 2019-11-28
        • 1970-01-01
        • 1970-01-01
        • 2020-08-14
        • 2019-06-21
        • 1970-01-01
        • 2023-03-19
        • 2014-04-15
        • 2011-01-04
        相关资源
        最近更新 更多