簡體   English   中英

根據列值刪除 Pandas 中的行

[英]Drop Rows in Pandas Based on Column Value

我正在使用 Pandas 創建一個具有數百行的 df,而 web 正在抓取一個體育網站。 我正在嘗試根據某一列的值解析行並刪除行。 我嘗試瀏覽 W3 和其他網站以找到正確的方法,但我發現的任何東西似乎都無法滿足我的需要。 我在下面列出了我的代碼。 有誰知道實現這一目標的好方法?

import pandas as pd

def rec_career():
    url = 'https://www.pro-football-reference.com/years/2022/receiving.htm'
    base_url = 'https://www.pro-football-reference.com'
    #Establish Dictionary
    player_links = dict()
    # Use Pandas to read table
    table = pd.read_html(url, attrs={'id': 'receiving'})[0]
    table.head()
    table.index = range(len(table))
    for i, row in table.iterrows():
        if row[4] != 'WR' or 'TE':
            table = table.drop(index=i)
    print(table)

rec_career()

上面的代碼返回一個空數據庫,因此它顯然只是解析並刪除所有行,但我不確定它為什么這樣做。 我基本上試圖從 df 中刪除不是接收器的玩家。

避免在 pandas 中使用for循環,因為 pandas 有更快更簡潔的方法:

...
table = pd.read_html(url, attrs={'id': 'receiving'})[0]
table.head()
table.index = range(len(table))
table = table[table.Pos.isin(['WR', 'TE'])]
print(table)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM