我有一个日期时间列的数据框架,如下所示:
dates
0 2017-09-19
1 2017-08-28
2 2017-07-13我想知道是否有办法在这种情况下调整日期:
我想要的输出应该如下所示:
dates
0 2017-09-30
1 2017-08-31
2 2017-06-30发布于 2022-08-28 19:36:32
使用np.where和乔希关于MonthEnd的建议,这可以简化一点。
给予:
dates
0 2017-09-19
1 2017-08-28
2 2017-07-13做:
from pandas.tseries.offsets import MonthEnd
# Where the day is less than 15,
# Give the DateEnd of the previous month.
# Otherwise,
# Give the DateEnd of the current month.
df.dates = np.where(df.dates.dt.day.lt(15),
df.dates.add(MonthEnd(-1)),
df.dates.add(MonthEnd(0)))
print(df)
# Output:
dates
0 2017-09-30
1 2017-08-31
2 2017-06-30发布于 2022-08-28 19:13:01
易于使用MonthEnd
让我们设置数据:
dates = pd.Series({0: '2017-09-19', 1: '2017-08-28', 2: '2017-07-13'})
dates = pd.to_datetime(dates)然后:
from pandas.tseries.offsets import MonthEnd
pre, post = dates.dt.day < 15, dates.dt.day >= 15
dates.loc[pre] = dates.loc[pre] + MonthEnd(-1)
dates.loc[post] = dates.loc[post] + MonthEnd(1)说明:首先创建掩码(pre和post)。然后,根据情况,使用掩码将当前或前一个月的月结束。
https://stackoverflow.com/questions/73521449
复制相似问题