首页 > 解决方案 > 根据数据框年份和月份删除行

问题描述

我知道这个问题可能已经以某种方式被问过,但是对于 python 来说是新手并且仍然遇到问题。我从 2020 年 4 月开始提取不完整的数据,现在我正在尝试从数据框中删除 2020 年 4 月的数据和/或创建一个不包括 2020 年 4 月的新数据框。

我将日期时间转换为年和月。数据框:cdf2 到目前为止创建了一个掩码:

cdf2['year']=pd.DatatimeIndex(cdf2['Invoice Paid Date']).year
cdf2['month']=pd.DatatimeIndex(cdf2['Invoice Paid Date']).month
mask= cdf2=cdf2[(cdf2['year']==2020.0) & (cdf2['month']==4.0)]

试图做cdf3=cdf2[~mask],但这不起作用

任何帮助,将不胜感激。谢谢

标签: pythonpandas

解决方案


这是一种方法:

首先,我创建了一个测试数据框,日期分别为 3 月、4 月和 5 月。

import pandas as pd

invoice_date = pd.date_range(start='2020-03-01', end='2020-05-15', freq='14d')
amt = [100 + i for i in range(len(invoice_date))]
df = pd.DataFrame({'invoice_date': invoice_date, 'amt': amt})
print(df)

  invoice_date  amt
0   2020-03-01  100
1   2020-03-15  101
2   2020-03-29  102
3   2020-04-12  103
4   2020-04-26  104
5   2020-05-10  105

然后,我创建并应用了一个布尔蒙版。我在面具中使用了日期。我没有为月份和年份创建新列。

mask = ('2020-04-01' <= df['invoice_date']) & (df['invoice_date'] <= '2020-04-30')
trimmed = df[~ mask]
print(trimmed)

  invoice_date  amt
0   2020-03-01  100
1   2020-03-15  101
2   2020-03-29  102
5   2020-05-10  105

推荐阅读