我读取了通常如下格式的excel文件:
colA colB
0 0
1 1
我可以写一些像 df = pd.read_excel(filename, skiprows=0)
跳过列标题并提取数据。但是有时我的数据以
some random text in the cells above
colA colB
0 0
1 1
在这里,我需要手动删除该多余的行,然后向上移动所有内容,以便第一行由列标题组成。是否有一种优雅的方法可以在发现任何行号colA的情况下启动excel读取,因此我们跳过了colA和colB标头上方的任何不必要的条目或文本?
假设您知道第一列名称(colA
例如,在您的示例中),并且该值将出现在数据的第一列中:
if df.columns[0] != "colA": # Check first if column name is incorrect.
# Get the first column of data:
first_col = df[df.columns[0]]
# Identify the row index where the value equals the column name:
header_row_index = first_col.loc[first_col == "colA"].index[0]
# Grab the column names:
column_names = df.loc[header_row_index]
# Reset the df to start below the new header row, and rename the columns:
df = df.loc[header_row_index+1:, :]
df.columns = column_names
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句