如何使用 iloc 删除 pandas 数据框中的第一行和最后一行
How to remove first and last row in pandas dataframe using iloc
我们如何使用 iloc
方法一次性删除 pandas dataframe
中的第一行和最后一行,例如 [[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)
您可以使用过滤来代替丢弃:
df = pd.read_html(r.text)[1].iloc[1:-1]
这将使您到达从中国到也门的每个国家/地区。
我们如何使用 iloc
方法一次性删除 pandas dataframe
中的第一行和最后一行,例如 [[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)
您可以使用过滤来代替丢弃:
df = pd.read_html(r.text)[1].iloc[1:-1]
这将使您到达从中国到也门的每个国家/地区。