【问题标题】:delete rows based on data frame year and month根据数据框年份和月份删除行
【发布时间】:2020-11-21 16:31:54
【问题描述】:

我知道这个问题可能已经以某种方式被问过,但是对于 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],但这不起作用

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

【问题讨论】:

  • 只是 cdf2[~((cdf2['year']==2020.0) & (cdf2['month']==4.0))] 不工作?
  • @SayandipDutta 谢谢。那行得通。

标签: python pandas


【解决方案1】:

这是一种方法:

首先,我创建了一个测试数据框,日期分别为 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

【讨论】:

  • 感谢您的帮助。我尝试了你的方法,但使用 trimmed.tail() 时,2020 年 4 月的月份仍然存在。所以,我最终从上面使用了 Sayandip Dutta 的方法。
猜你喜欢
  • 2021-11-25
  • 2019-12-06
  • 2012-02-24
  • 2016-11-05
  • 1970-01-01
  • 2018-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多