简体   繁体   English

从 Excel-Python 读取时如何替换标题行

[英]how to replace the header row when reading from Excel- Python

I am reading an Excel file, and I want to extract some tables from it, and put the same header for each of them.我正在阅读一个 Excel 文件,我想从中提取一些表格,并为每个表格放置相同的标题。

It is now taking the first row as the header, while the actual header is the 3rd row.它现在将第一行作为标题,而实际的标题是第三行。

Here is what I did:这是我所做的:

new_header = df.iloc[1]
df = df[3:] #choose the data
df.rename(columns = new_header)

But it does not change the header row.但它不会更改标题行。 Any help is appreciated.任何帮助表示赞赏。

UPDATE: @EdChum's answer solves the header issue.更新:@EdChum 的回答解决了标题问题。 However I have problem with the format of the header.但是我对标题的格式有问题。 The header is date in the format of Month-Year and I want to keep it that way.标题是Month-Year格式的日期,我想保持这种方式。 But when it reades it, it changes the format to "2014-01-01 00:00:00" .但是当它读取它时,它将格式更改为"2014-01-01 00:00:00" I wrote the following peice to fix it, but it only changes the firt cell format and thus, cannot use it as the new header.我写了以下 peice 来修复它,但它只更改了第一个单元格格式,因此不能将其用作新标题。

new_header = datetime.datetime.strptime("2014-01-01 00:00:00", '%Y-%m-%d %H:%M:%S').strftime('%b-%y')

Assign directly直接赋值

df.columns = new_header

Also you need to assign the result back:您还需要将结果分配回:

df = df.rename(columns = new_header)

as inplace=False is the default value, most pandas ops return a copy and are not inplace.由于inplace=False是默认值,大多数 Pandas 操作返回一个副本并且不是就地的。

If you did如果你做了

df.rename(columns = new_header, inplace=True)

it would work它会工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM