但是,如果我只需要像下面这样通过iloc获取第一行和最后一行,我们如何使用iloc方法在像[[0:, :-1]]这样的一步操作中删除pandas dataframe中的第一行和最后一行。
DataFrame:
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)发布于 2020-04-25 21:54:03
您可以使用过滤,而不是删除:
df = pd.read_html(r.text)[1].iloc[1:-1]这将把你带到从中国到也门的每个国家。
https://stackoverflow.com/questions/61426632
复制相似问题