删除pandas中某个字符串后的行

时间:2017-03-15 17:48:29

标签: python pandas dataframe

我想删除包含字符串"第4季度结束"的行之后的所有行。目前,这是第474行,但它会根据游戏而改变。

from bs4 import BeautifulSoup
import requests
import pandas as pd
import re

url = "http://www.espn.com/nba/playbyplay?gameId=400900395"
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data,"html.parser")

data_rows = soup.findAll("tr")[4:]

play_data = []
for i in range(len(data_rows)):
    play_row = []

    for td in data_rows[i].findAll('td'):
        play_row.append(td.getText())

    play_data.append(play_row)

df = pd.DataFrame(play_data)

df.to_html("pbp_data")

3 个答案:

答案 0 :(得分:3)

以下是我将如何处理它:

ur_row = your_df.ix[your_df['Column_Name_Here']=='End of the 4th Quarter'].index.tolist()

ur_row获取满足条件的行的索引号。然后我们使用切片来获得每一行。 (+1将捕获包括“第4季度结束”的行

df.iloc[:ur_row[0]+1]

希望这很容易理解。如果需要,我会很乐意解释更多!

答案 1 :(得分:2)

如果您确定数据框中某处存在这样的字符串,则可以使用idxmax()找出相应的索引,然后使用loc取出索引前的所有行:< / p>

df.loc[:(df == 'End of the 4th Quarter').any(1).idxmax()]

最后几行:

df.loc[:(df == 'End of the 4th Quarter').any(1).idxmax()].tail()

enter image description here

答案 2 :(得分:0)

通过以下方式确定行的索引:

row = df[df['Column Name'] == 'End of the 4th quarter'].index.tolist()[0]

然后通过以下方式仅保留行至该行:

df = df.iloc[:row-1]
相关问题