根据日期删除行

时间:2021-07-12 20:33:07

标签: python pandas dataframe time-series drop

Python 专家您好, 我将数据从 2021 年 4 月的 csv 文件导入到 python 数据帧中。但是我想在 2019 年之后删除任何数据。尝试使用 data.drop() 功能,但似乎无法弄清楚语法。如何删除数据框中 2019 年之后的所有数据?

请查看我的代码和 csv 文件(正在创建数据框的表单)和建议。谢谢! 将熊猫导入为 pd 导入日期时间 将 matplotlib.pyplot 导入为 plt

if __name__ == '__main__':
index_data =pd.read_csv('CSUSHPISA.csv')
index_data['DATE'] =pd.to_datetime(index_data['DATE'])
index_data.set_index('DATE', inplace=True)

print(index_data)

当前结果:
enter image description here

data.drop()????

3 个答案:

答案 0 :(得分:2)

试试loc

index_data.loc[:"2019"]

答案 1 :(得分:0)

您可以通过以下方式实现:

index_data.drop(index_data[index_data['DATE'].dt.year > 2019].index, inplace = True)

答案 2 :(得分:0)

您可以使用用于过滤 Pandas 数据帧 (docs) 的 .loc 方法,例如:

import pandas as pd
index_data = pd.read_csv(r'https://fred.stlouisfed.org/graph/fredgraph.csv?bgcolor=%23e1e9f0&chart_type=line&drp=0&fo=open%20sans&graph_bgcolor=%23ffffff&height=450&mode=fred&recession_bars=on&txtcolor=%23444444&ts=12&tts=12&width=1168&nt=0&thu=0&trc=0&show_legend=yes&show_axis_titles=yes&show_tooltip=yes&id=CSUSHPISA&scale=left&cosd=1987-01-01&coed=2021-04-01&line_color=%234572a7&link_values=false&line_style=solid&mark_type=none&mw=3&lw=2&ost=-99999&oet=99999&mma=0&fml=a&fq=Monthly&fam=avg&fgst=lin&fgsnd=2020-02-01&line_index=1&transformation=lin&vintage_date=2021-07-12&revision_date=2021-07-12&nd=1987-01-01')
index_data['DATE'] = pd.to_datetime(index_data['DATE'])
index_data.set_index('DATE', inplace=True)

print(index_data.loc[index_data.index.year <= 2019])

结果:

            CSUSHPISA
DATE                 
1987-01-01     63.967
1987-02-01     64.426
1987-03-01     64.736
1987-04-01     65.135
1987-05-01     65.569
...               ...
2019-08-01    210.422
2019-09-01    211.062
2019-10-01    211.649
2019-11-01    212.438
2019-12-01    213.365

[396 rows x 1 columns]