【问题标题】:Pandas: select all dates with specific month and day熊猫:选择具有特定月份和日期的所有日期
【发布时间】:2015-04-18 14:50:59
【问题描述】:

我有一个包含日期的数据框,我想选择月份==12 和日期==25 的所有日期,并添加将xmas 列中的零替换为 1。

无论如何要这样做?我的代码第二行出错了。

df = DataFrame({'date':[datetime(2013,1,1).date() + timedelta(days=i) for i in range(0,365*2)], 'xmas':np.zeros(365*2)})

df[df['date'].month==12 and df['date'].day==25] = 1

【问题讨论】:

  • 你想要这个:df.loc[(df['date'].month==12) & (df['date'].day==25), 'xmas'] = 1
  • 为了更容易看到,你现在有了 datetime 属性,允许你写像df['date'].dt.month == 12 这样的东西。

标签: python datetime pandas


【解决方案1】:

带有 datetime 的 Pandas Series 现在的行为有所不同。见.dt accessor

现在应该这样做:

df.loc[(df['date'].dt.day==25) & (cust_df['date'].dt.month==12), 'xmas'] = 1

【讨论】:

    【解决方案2】:

    基本上您尝试的方法不起作用,因为您需要使用& 来比较数组,此外,由于运算符优先级,您还需要使用括号。除此之外,您应该使用loc 来执行索引:

    df.loc[(df['date'].month==12) & (df['date'].day==25), 'xmas'] = 1
    

    【讨论】:

    • 我的经验给了我一个关于列名的错误,但我只是用df.index 代替了df['date'],然后它就像你展示的那样工作。
    • 如果月份是 6 ,7 8 9,那么超过一个月呢?
    猜你喜欢
    • 2023-03-31
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 2021-12-15
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    相关资源
    最近更新 更多