首先在read_csv 中使用index_col 和parse_dates 参数创建DatetimeIndex:
df = pd.read_csv("path/to/my/file/myfile.csv",
index_col=['report_date'],
parse_dates=['report_date'])
然后可以使用DataFrame.last:
df1 = df.last('10d')
最后由DataFrame.to_csv保存到文件:
df1.to_csv('new.csv')
您的解决方案应更改为将read_csv 中的列转换为日期时间:
df = pd.read_csv("path/to/my/file/myfile.csv", parse_dates=['report_date'])
days=10
cutoff_date = df["report_date"].dt.date.iloc[-1] - pd.Timedelta(days=days)
然后通过Series.dt.date 在boolean indexing 中比较日期:
df1 = df[df["report_date"].dt.date > cutoff_date]
上次保存到文件并删除默认索引的DataFrame.to_csv:
df1.to_csv('new.csv', index=False)
编辑:我相信你需要:
df = pd.DataFrame({'data': range(30)}, index= pd.date_range('2020-01-25', periods=30))
print (df)
data
2020-01-25 0
2020-01-26 1
2020-01-27 2
2020-01-28 3
2020-01-29 4
2020-01-30 5
2020-01-31 6
2020-02-01 7
2020-02-02 8
2020-02-03 9
2020-02-04 10
2020-02-05 11
2020-02-06 12
2020-02-07 13
2020-02-08 14
2020-02-09 15
2020-02-10 16
2020-02-11 17
2020-02-12 18
2020-02-13 19
2020-02-14 20
2020-02-15 21
2020-02-16 22
2020-02-17 23
2020-02-18 24
2020-02-19 25
2020-02-20 26
2020-02-21 27
2020-02-22 28
2020-02-23 29
today = pd.Timestamp('today').floor('d')
df1 = df[df.index > today].first('10d')
print (df1)
data
2020-02-11 17
2020-02-12 18
2020-02-13 19
2020-02-14 20
2020-02-15 21
2020-02-16 22
2020-02-17 23
2020-02-18 24
2020-02-19 25
2020-02-20 26