我目前正在做一个项目,我必须从一个 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 很陌生,所以任何帮助都将不胜感激。
非常感谢!
我无法测试,因为您没有给出数据示例,但是根据this和this答案,您可以尝试:
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句