python - 根据数据框年份和月份删除行
问题描述
我知道这个问题可能已经以某种方式被问过,但是对于 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]
,但这不起作用
任何帮助,将不胜感激。谢谢
解决方案
这是一种方法:
首先,我创建了一个测试数据框,日期分别为 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
推荐阅读
- mongodb - Monk - 为什么我的更新有时只有效?
- python - 添加 order_by 时 Django 管理员性能糟糕的 get_form 查询集过滤器
- eclipse - 为 JSF 下载 Mojarra 库时,在 Eclipse 中显示错误“zip 文件为空”
- rust - 如何在泛型类型上调用关联函数?
- java - Spring Batch给出所有要写入的字节都没有成功写入错误
- .net - IdentityServer 中的多个 jwks
- r - 在 R 中创建循环以使用比较运算符(>、<、== 等)查找向量的最小值
- javascript - 谷歌地图街景是灰色的(抛出错误 b.hasAttribute is not a function)
- excel - 从 SKU 中查找大小
- google-sheets - 平均 #DIV/0!解决方案?