Python 在数据帧列表中循环时删除数据帧的第一行
我正试图编写一个函数来循环遍历数据帧列表,其中包含我使用pd.read_html从网站中提取的表。我想删除每个数据帧中的第一行,并尝试使用我在下面编写的函数,但它不起作用。有人知道为什么吗Python 在数据帧列表中循环时删除数据帧的第一行,python,pandas,Python,Pandas,我正试图编写一个函数来循环遍历数据帧列表,其中包含我使用pd.read_html从网站中提取的表。我想删除每个数据帧中的第一行,并尝试使用我在下面编写的函数,但它不起作用。有人知道为什么吗 for df in df_list: df.columns = df.iloc[0] df.drop(df.index[0]) df_list[0] **Hospital/Location Specialty** 0 Hospital/Location Specialty
for df in df_list:
df.columns = df.iloc[0]
df.drop(df.index[0])
df_list[0]
**Hospital/Location Specialty**
0 Hospital/Location Specialty
1 Maimonides Med Ctr-NY Maimonides Med Ctr-NY Medicine-Preliminary Anesthesiology
2 Jacobi Med Ctr/Einstein-NY Pediatrics
3 Jacobi Med Ctr/Einstein-NY Pediatrics
4 Temple Univ Hosp-PA Internal Medicine
让我们把它分配回去
for idx, df in enumerate(df_list):
df.columns = df.iloc[0]
df_list[idx]=df.drop(df.index[0])
您需要将其分配回df 像这样,
df=df.drop(df.index[0])
它从我的数据帧中删除了索引0。数据帧现在从索引1开始 为什么不使用理解
# test data:
df1 = pd.DataFrame({0: ['col1', 'A', 'B'], 1: ['col2', '1', '2']})
df2 = pd.DataFrame({0: ['colA', 'a', 'b'], 1: ['colB', 'hello', 'goodbye']})
dfs = [df1, df2]
renamed = [d.rename(columns=df1.iloc[0]).drop(0) for d in dfs]
for df in renamed:
print(df)
# outputs:
col1 col2
1 A 1
2 B 2
colA colB
1 a hello
2 b goodbye
enumerate做什么?@gboge