索引未重置
Index not resetting
我有一个列表理解,在其中,我调用一个函数,向它传递两个参数。在该函数中,我有另一个列表推导式,它为我提供了一个 DataFrames 列表。
我必须清理每个 DataFrame 中的数据,所以我使用 for 循环遍历列表中的每个 DataFrame。在每次迭代中,我都会做任何我需要做的事情,其中之一就是重置每个 DataFrame 的索引。我在函数外放置了一个 print 语句,只是为了确保我按照我需要的方式获得所有内容,但索引没有被重置。为什么不重置?
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
我错过了什么?
提前致谢!
而不是
df = df.reset_index(drop=True)
使用
df.reset_index(drop=True, inplace=True)
问题是 df.reset_index()
returns 如果 inplace
是 False
的值,而你 已将 该值分配给 df
,但是您没有对 df
做任何进一步的事情。您正在使用数据框列表,并且该列表不包括您刚刚创建的新 local df
。
另一种选择是将新 df
存储在您的 df_list
中。这对我来说感觉像是更多的工作,因为 pandas 已经支持大多数操作的就地参数。
我有一个列表理解,在其中,我调用一个函数,向它传递两个参数。在该函数中,我有另一个列表推导式,它为我提供了一个 DataFrames 列表。
我必须清理每个 DataFrame 中的数据,所以我使用 for 循环遍历列表中的每个 DataFrame。在每次迭代中,我都会做任何我需要做的事情,其中之一就是重置每个 DataFrame 的索引。我在函数外放置了一个 print 语句,只是为了确保我按照我需要的方式获得所有内容,但索引没有被重置。为什么不重置?
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
我错过了什么?
提前致谢!
而不是
df = df.reset_index(drop=True)
使用
df.reset_index(drop=True, inplace=True)
问题是 df.reset_index()
returns 如果 inplace
是 False
的值,而你 已将 该值分配给 df
,但是您没有对 df
做任何进一步的事情。您正在使用数据框列表,并且该列表不包括您刚刚创建的新 local df
。
另一种选择是将新 df
存储在您的 df_list
中。这对我来说感觉像是更多的工作,因为 pandas 已经支持大多数操作的就地参数。