Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:在今天之前移除年-周行?_Python_Pandas_Dataframe_Datetime - Fatal编程技术网

Python 熊猫:在今天之前移除年-周行?

Python 熊猫:在今天之前移除年-周行?,python,pandas,dataframe,datetime,Python,Pandas,Dataframe,Datetime,我想从数据框中删除本周之前的行。然而,预期的代码不起作用,因为一位数的周数仍在出现。有更好的办法吗 import pandas as pd import numpy as np from datetime import date, datetime, timedelta data = { "Year": [2019, 2020, 2020, 2020, 2020, 2020, 2020], "Week": [40, 8, 9, 10, 11, 12, 13] } df = pd

我想从数据框中删除本周之前的行。然而,预期的代码不起作用,因为一位数的周数仍在出现。有更好的办法吗

import pandas as pd
import numpy as np
from datetime import date, datetime, timedelta

data = {
    "Year": [2019, 2020, 2020, 2020, 2020, 2020, 2020],
    "Week": [40, 8, 9, 10, 11, 12, 13]
}
df = pd.DataFrame(data)

# Current YearWeek
year_week = datetime.now().strftime("%Y/W%V")
print(year_week)

df["Year/Week"] = pd.to_datetime(
    (df["Year"].astype(str) + "/W" + df["Week"].astype(str)),
    format="%Y/W%V",
    errors="ignore")

# Drop rows that have Year-Week value less than current Year-Week
df["Exclude Rows"] = np.where(
    pd.to_datetime(
        (df["Year"].astype(str) + "/W" + df["Week"].astype(str)),
        format="%Y/W%V",
        errors="ignore",
    ) < year_week, "Yes", "No")

# Drop rows
df.drop(df.loc[df["Exclude Rows"] == "Yes"].index, inplace=True)

print(df)

以下是一个可能的解决方案,灵感来自:

将熊猫作为pd导入
从日期时间导入日期时间
数据={
“年份”:[2019年、2020年、2020年、2020年、2020年、2020年、2020年],
“一周”:[40,8,9,10,11,12,13]
}
df=pd.DataFrame(数据)
df=df[pd.to_datetime(df.Year.astype(str),格式='%Y')+\
pd.to_timedelta(df.Week.mul(7).astype(str)+“days”)
>datetime.now()
]

结果:

   Year  Week
5  2020    12
6  2020    13

以下是一个可能的解决方案,灵感来自:

将熊猫作为pd导入
从日期时间导入日期时间
数据={
“年份”:[2019年、2020年、2020年、2020年、2020年、2020年、2020年],
“一周”:[40,8,9,10,11,12,13]
}
df=pd.DataFrame(数据)
df=df[pd.to_datetime(df.Year.astype(str),格式='%Y')+\
pd.to_timedelta(df.Week.mul(7).astype(str)+“days”)
>datetime.now()
]

结果:

   Year  Week
5  2020    12
6  2020    13