【问题标题】:Days before end of month in pandas大熊猫月底前的几天
【发布时间】:2023-03-09 06:38:01
【问题描述】:

我想从表示日期的字符串列中获取月底前的天数。 我有以下熊猫数据框:

df = pd.DataFrame({'date':['2019-11-22','2019-11-08','2019-11-30']})
df

         date
0  2019-11-22
1  2019-11-08
2  2019-11-30

我想要以下输出:

 df
         date  days_end_month
0  2019-11-22               8
1  2019-11-08              22
2  2019-11-30               0

pd.tseries.MonthEndrollforward 包似乎是一个不错的选择,但我不知道如何使用它来转换整个列。

【问题讨论】:

  • 这可以做到:df['days_end_month'] = pd.Period(df['date']).days_in_month - df['date'].dt.day

标签: python pandas


【解决方案1】:

Series.dt.day提取的天数减去Series.dt.daysinmonth创建的月份的所有天数:

df['date'] = pd.to_datetime(df['date'])

df['days_end_month'] = df['date'].dt.daysinmonth - df['date'].dt.day

或者使用offsets.MonthEnd,将时间增量减去Series.dt.days并将其转换为天数:

df['days_end_month'] = (df['date'] + pd.offsets.MonthEnd(0) - df['date']).dt.days

print (df)
        date  days_end_month
0 2019-11-22               8
1 2019-11-08              22
2 2019-11-30               0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-20
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多