pandas 将熊猫数据框的第一行转换为列名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52516199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:03:01  来源:igfitidea点击:

Convert first row of pandas dataframe to column name

pythonpandas

提问by Hariom Singh

I have a pandas dataframe

我有一个Pandas数据框

   0     1     2
0  pass fail  warning
1  50    12    34

I am trying to convert first row as column name something like this

我正在尝试将第一行转换为类似这样的列名

   pass fail  warning
0  50    12    34

I am currently doing this by renaming the column name

我目前正在通过重命名列名来做到这一点

 newdf.rename(columns={0: 'pass', 1: 'fail', 2:'warning'})

and then deleting the first row. Any better way to do it .

然后删除第一行。任何更好的方法来做到这一点。

采纳答案by jezrael

I believe need to add parameter to read_html:

我相信需要将参数添加到read_html

df = pd.read_html(url, header=1)[0]

Or:

或者:

df = pd.read_html(url, skiprows=1)[0]

回答by Vidya P V

For the dataframe DF, the following line of code will set the first row as the column names of the dataframe:

对于数据框 DF,以下代码行将第一行设置为数据框的列名:

DF.columns = DF.iloc[0]