在Python中使用pandas仅显示excel中的某些行时出现问题

问题描述 投票:0回答:1

我知道我的代码非常凌乱,可能看起来很糟糕,但作为一名业余爱好者,我正在尝试创建简单的代码,以允许我看到特定高速公路的计划关闭。我每天都设法提取出想要的表格和我想要的专栏。我现在遇到的唯一问题是仅显示以“M5”和“M6”字符串开头的行。我尝试了 .str.startwith("M6"),但总是给我一个错误。也尝试实现.str.contains,效果一样。

from datetime import datetime
import pandas as pd

url = 'https://nationalhighways.co.uk/media/s2pjwbuk/7-day-closure-report-26-july-web-upload.xls'
dt = datetime.now()
x = dt.weekday()
column_name = [5]

print(x)

if x == 0:
    sheet_name = "Monday"
    data = pd.read_excel(url, sheet_name, usecols=column_name)
    print(data)
if x == 1:
    sheet_name = "Tuesday"
    data = pd.read_excel(url, sheet_name, usecols=column_name)
    print(data)
if x == 2:
    sheet_name = "Wednesday"
    data = pd.read_excel(url, sheet_name, usecols=column_name)
    print(data)
if x == 3:
    sheet_name = "Thursday"
    data = pd.read_excel(url, sheet_name, usecols=column_name)
    print(data)

if x == 4:
    sheet_name = "Friday"
    data = pd.read_excel(url, sheet_name, usecols=column_name)
    print(data)
if x > 4:
    sheet_name = "Monday"
    data = pd.read_excel(url, sheet_name, usecols=column_name)
    print(data)

data = pd.read_excel(url,sheet_name,usecols=column_name.str.startwith(“M6”))

打印(data.str.包含“M6”)

python pandas excel parsing xls
1个回答
0
投票

您可以在函数链内使用 .query()

代码:

from datetime import datetime

import pandas as pd


today = datetime.now().strftime("%A")

url = "https://nationalhighways.co.uk/media/s2pjwbuk/7-day-closure-report-26-july-web-upload.xls"

df = (pd
      .read_excel(io=url, sheet_name=today, skiprows=1, usecols=["Closure details, including diversions"])
      .rename(columns={"Closure details, including diversions": "closures"})
      .query("closures.str.startswith('M5') | closures.str.startswith('M6')")
      .drop_duplicates()
      .reset_index(drop=True)
      )
print(df)

输出:

                                                                                               closures
0                                  M56 Eastbound link road closure to A34 Northbound due to gas works 
1  M6 Southbound junction 27 to junction 26 - Carriageway Closure for Horticulture (Cutting and Pla...
2  M6 North & Southbound Junction 21A - 26 lane closures and carriageway closures due to improvemen...
3        M6 southbound Jct 13 to jct 12 \ncarriageway closure for carriageway - reconstruction/renewal
4  M62 eastbound and westbound Jct 36 to Western Interchange.\nCarriageway closures for survey work...
5  M62 westbound Jct 29 to Jct 27 and m62 westbound jct 29 entry slip closed \nCarriageway closure ...
6  M621 anticlockwise Jct 7 to Jct 1.\nCarriageway and lane closures including narrow lanes and spe...
7                                                   M65 eastbound J5 to J7 - lane closure for barriers
8      M67 Eastbound and Westbound J1a to J3 - Carriageway Closure for Structure - New/Reconstruction 
© www.soinside.com 2019 - 2024. All rights reserved.