【问题标题】:How to remove first and last row in pandas dataframe using iloc如何使用 iloc 删除熊猫数据框中的第一行和最后一行
【发布时间】:2020-08-09 02:30:31
【问题描述】:

我们如何使用iloc 方法在一个步骤中删除熊猫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)

【问题讨论】:

    标签: pandas dataframe python-3.6


    【解决方案1】:

    您可以使用过滤代替丢弃:

    df = pd.read_html(r.text)[1].iloc[1:-1]
    

    这将为您提供从中国到也门的每个国家/地区。

    【讨论】:

    • 优秀的@Code 不同,我的错误我使用的是.iloc[1:, -1] ...谢谢+1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多