首页 > 解决方案 > 运行 Python 代码时的另一个回溯错误

问题描述

我有一个新的 Traceback 错误,当我运行我的 Python 代码时。它似乎与我的代码中最后一个 ) 括号有关,也可能是最后一个 ] 。

((df['Location'].str.contains('- Display')) & 
                df['Lancaster'] != 'L' & 
                df['Dakota'] == 'D' & 
                df['Spitfire'] == 'SS' &
                df['Hurricane'] != 'H'))
              )]      

这是我得到的回溯错误:

        File "<ipython-input-5-6d53e7e5ec10>", line 31
        )
        ^
    SyntaxError: invalid syntax  

这是我最新的完整代码 John S,它有效。我会告诉你,如果我遇到更多问题,非常感谢你的帮助:

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')) & (df['Lancaster'] != 'L')]     
display </code>

标签: pythonpython-3.xpandasjupyter-notebook

解决方案


您需要在最后添加“)]”。所以你可变的南港将是现在

Southport = df[
    (
        ((df['Location'].str.contains('- Display') & 
        df['Lancaster'] != 'L' & 
        df['Dakota'] == 'D' & 
        df['Spitfire'] == 'S' & 
        df['Hurricane'] == 'H'))
    )
] | df[
    (
        ((df['Location'].str.contains('- Display') & 
        df['Lancaster'] != 'L' & 
        df['Dakota'] == 'D' & 
        df['Spitfire'] == 'S' &
        df['Hurricane'] != 'H'))
    )
] | df[
    (
        ((df['Location'].str.contains('- Display') & 
        df['Lancaster'] != 'L' & 
        df['Dakota'] == 'D' & 
        df['Spitfire'] == 'SS' &
        df['Hurricane'] != 'H'))
     )]

推荐阅读