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

jvlzgdj9  于 2023-08-01  发布在  Python
关注(0)|答案(1)|浏览(117)

我知道我的代码是超级不整洁,可能看起来很可怕,但作为甚至不是业余的,我试图创建简单的代码,让我看到计划关闭的特定高速公路。我每天都能抽出我想要的表格和专栏。我现在唯一的问题是只显示以“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)

字符串
数据= pd.read_excel(url,sheet_name,usecols=column_name.str.startwith(“M6”))
或者是
print(data.str.contains“M6”)

9nvpjoqh

9nvpjoqh1#

你可以在函数链中使用.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

相关问题