如何从以下数据框中删除第一行并将行的设置index = 0
为header?谢谢。
0 ... 8 ---> row without index to exclude which is header of current dataframe
0 id ... date ---> row to set as header
1 1 ... 2020-01-23
2 2 ... 2020-01-23
3 3 ... 2020-01-23
4 4 ... 2020-01-23
5 5 ... 2020-01-23
6 6 ... 2020-01-23
7 7 ... 2020-01-23
8 8 ... 2020-01-23
9 9 ... 2020-01-23
10 10 ... 2020-01-23
当我打印时df.columns
,它会生成Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8], dtype='int64')
。
完整代码:
import requests
import json
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
for page in range(1, 3):
data = {
'filter_LIKE_GCMC': '',
'filter_LIKE_JSDWMC': '',
'filter_LIKE_SGDWMC': '',
'filter_LIKE_BABH': '',
'currentPage': page,
'pageSize': '15',
'OrderByField': '',
'OrderByDesc': ''
}
website_url = requests.post('http://bjjs.zjw.beijing.gov.cn/eportal/ui?pageId=308894', data = data).text
soup = BeautifulSoup(website_url, 'html.parser')
table = soup.find('table', {'class': 'gridview'})
#https://stackoverflow.com/questions/51090632/python-excel-export
df = pd.read_html(str(table), skiprows=0)[0]
# df = pd.read_html(str(table))[0]
# df.columns = df.iloc[0]
# df = df.iloc[1:]
# print(df.head(5))
print(df)
输出:
0 ... 8 ---> row without index to exclude
0 序号 ... 竣工备案日期 ---> row to set as header
1 1 ... 2020-01-23
2 2 ... 2020-01-23
3 3 ... 2020-01-23
4 4 ... 2020-01-23
5 5 ... 2020-01-23
6 6 ... 2020-01-23
7 7 ... 2020-01-23
8 8 ... 2020-01-23
9 9 ... 2020-01-23
10 10 ... 2020-01-23
11 11 ... 2020-01-23
12 12 ... 2020-01-22
13 13 ... 2020-01-22
14 14 ... 2020-01-22
15 15 ... 2020-01-22
[16 rows x 9 columns]
0 ... 8 ---> row without index to exclude
0 序号 ... 竣工备案日期 ---> row to set as header
1 16 ... 2020-01-22
2 17 ... 2020-01-22
3 18 ... 2020-01-22
4 19 ... 2020-01-22
5 20 ... 2020-01-22
6 21 ... 2020-01-22
7 22 ... 2020-01-22
8 23 ... 2020-01-22
9 24 ... 2020-01-22
10 25 ... 2020-01-22
11 26 ... 2020-01-22
12 27 ... 2020-01-22
13 28 ... 2020-01-22
14 29 ... 2020-01-22
15 30 ... 2020-01-21
[16 rows x 9 columns]
如果可能的话,最好在此处将第二行设置为DataFrame列,这是创建的DataFrame的方法,在这里read_html
:
df = pd.read_html(str(table), skiprows=0)[0]
#or
df = pd.read_html(str(table), skiprows=1)[0]
要么:
df = pd.read_html(str(table), header=1)[0]
如果不可能,请使用上述解决方案:
df.columns = df.iloc[0]
df = df.iloc[1:]
编辑:输出为df = pd.read_html(str(table), skiprows=0)[0]
熊猫0.25.1:
序号 工程名称 建设单位 \
0 1 朝阳区三里屯路19号院9号楼S09-1-局部内外装修工程 北京三里屯南区物业管理有限公司
1 2 改善办学保障条件-基础设施改造-定额管理项目2-芍药居校区整体改造二期工程2标段(阶梯教室、... 北京服装学院
建设单位项目负责人 施工单位 施工单位项目负责人 编号 备案部门 \
0 冯锐 北京菲尼有限公司 徐广辉 0076朝竣2020(装)0064号 北京市朝阳区住房和城乡建设委员会
1 兰泰黔 北京广佳建设股份有限公司 卿朵 0074朝竣2020(装)0062号 北京市朝阳区住房和城乡建设委员会
竣工备案日期
0 2020-01-23
1 2020-01-23
序号 工程名称 建设单位 \
0 16 朝阳区酒仙桥北路甲10号院205号楼1层2层内装修工程 北京美伸医学影像诊断中心有限公司
1 17 F座办公楼(中关村科技园电子城西区二期A6地块项目)11至12层(电梯楼层12至13层)局部... 鸿合科技股份有限公司
建设单位项目负责人 施工单位 施工单位项目负责人 编号 备案部门 \
0 岳洋 北京朋利嘉业装饰工程有限公司 李宗仓 0063朝竣2020(装)0051号 北京市朝阳区住房和城乡建设委员会
1 刘秀铭 北京盛茂盛建设工程有限公司 李艳华 0064朝竣2020(装)0052号 北京市朝阳区住房和城乡建设委员会
竣工备案日期
0 2020-01-22
1 2020-01-22
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句