如何使用dataframe
之类的iloc
方法删除熊猫[[0:, :-1]]
中的第一行和最后一行,但是如果我只需要通过来获取第一行和最后一行iloc
如下。
import pandas as pd
import numpy as np
import requests
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('expand_frame_repr', True)
header={"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36", "X-Requested-With":"XMLHttpRequest"}
url = 'https://www.worldometers.info/coronavirus/'
r = requests.get(url, headers=header)
#read second table in url
df = pd.read_html(r.text)[1].iloc[[0, -1]]
#replace nan to zero
df = df[['Country,Other', 'TotalCases', 'NewCases', 'TotalDeaths', 'NewDeaths', 'TotalRecovered', 'ActiveCases', 'Serious,Critical']].replace(np.nan, "0")
print(df)
在下面,我可以获取需要删除的第一个和最后一个。
Country,Other TotalCases NewCases TotalDeaths NewDeaths TotalRecovered ActiveCases Serious,Critical
0 World 2828826 +105,825 197099.0 +6,182 798371.0 1833356 58531.0
213 Total: 2828826 +105,825 197099.0 +6,182 798371.0 1833356 58531.0
但是,我可以将最后一行删除为df = pd.read_html(r.text)[1].iloc[:-1]
,但是到目前为止,我还知道其他方式,如下所示,但是又分两步进行。
df.drop(df.tail(1).index,inplace=True)
df.drop(df.head(1).index,inplace=True)
答案 0 :(得分:1)
您可以使用过滤来代替丢弃:
df = pd.read_html(r.text)[1].iloc[1:-1]
这将带您从中国到也门的每个国家。