我有一个列表理解,并在其中调用一个函数,并传递给它两个参数。在该函数中,我有另一个列表推导式,它为我提供了一个 DataFrame 列表。
我必须清理每个 DataFrame 中的数据,因此我使用 for 循环遍历列表中的每个 DataFrame。在每次迭代中,我会做任何我需要做的事情,其中一件事是重置每个 DataFrame 的索引。我在函数之外放置了一个打印语句,只是为了确保我按照我需要的方式获取所有内容,但不会重置索引。为什么不重置?
def function(xls, a_list):
# a_list is a list of strings
df_list = [pd.read_excel(xls, sheet_name=a) for a in a_list]
for df in df_list:
df.dropna(how='all', inplace=True)
df['Meal'] = df['Meal'].fillna(method='ffill')
# RIGHT HERE
df = df.reset_index(drop=True)
return df_list
# ------------------------------------
list_of_df = [function(xls, monthly_sheets) for xls, monthly_sheets in zip(xls_files, sheet_names) if monthly_sheets]
例如,这就是我得到的:
Col1 Col2
0 a f
1 b g
4 c h
7 d i
8 e j
我想要的是这个:
Col1 Col2
0 a f
1 b g
2 c h
3 d i
4 e j
我错过了什么?
holdtom
相关分类