首页 > 解决方案 > 我需要帮助在 Python 代码中进行数据排序

问题描述

在我的 Python 代码中,我还希望 Dakota with Hurricane 在 Jupyter Notebook 中运行时在数据表中显示外观。

我对代码进行了以下修改,旨在实现这一目标:-

(df['Spitfire'].str.contains('S', na=True))

现在是带有 Hurricane Display 预订的 Dakota,即在这种情况下,对于 Worthing - Display,该数据显示,Dakota Spitfire 和 Hurricane 以及带有 Spitfire Display Bookings 的 Dakota 也是如此。还有我不想显示的 Solo Dakota Display 预订。我要输入什么来启用,当 Dakota = 'D' 和 'Spitfire' = 'NaN' 和 'Hurricane' = 'NaN' 时,该行不显示?

我几乎已经设法在我的 Python 代码中整理出我需要做的事情,对于 2007 年的 Url,我只需要飓风预订问题的 Dakota,整理出这是我的代码,其中包含相关的 Url:-

import pandas as pd
import requests
from bs4 import BeautifulSoup

res = requests.get("http://web.archive.org/web/20070701133815/http://www.bbmf.co.uk/june07.html")
soup = BeautifulSoup(res.content,'lxml')
table = soup.find_all('table')[0]

df = pd.read_html(str(table))
df = df[1]
df = df.rename(columns=df.iloc[0])
df = df.iloc[2:]
df.head(15)

display = df[(df['Location'].str.contains('- Display')) & (df['Dakota'].str.contains('D')) & (df['Spitfire'].str.contains('S', na=True)) & (df['Lancaster'] != 'L')]     
display

任何帮助将非常感激。

问候

埃迪

标签: pythonpython-3.xpandasjupyter-notebookcode-cleanup

解决方案


您可以查询display变量以优化数据:

display = display[~((display['Dakota'] == 'D') & (display["Spitfire"].isnull() & (display['Hurricane'].isnull())))]

其中~用于否定条件,以便以下查询从 DataFrame 中排除元素。

您也可以将其包含在您的原始查询中df


推荐阅读