Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

python - Pandas: Change day

I have a series in datetime format, and need to change the day to 1 for each entry. I have thought of numerous simple solutions, but none of them works for me. For now, the only thing that actually works is

  • set the series as the index
  • Query month and year from the index
  • Reconstruct a new time series using year, month and 1

It can't really be that complicated, can it? There is month start, but is unfortunately an offset, that's of no use here. There seems to be no set() function for the method, and even less functionality while the series is a column, and not (part of) the index itself.

The only related question was this, but the trick used there is not applicable here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use .apply and datetime.replace, eg:

import pandas as pd
from datetime import datetime

ps = pd.Series([datetime(2014, 1, 7), datetime(2014, 3, 13), datetime(2014, 6, 12)])
new = ps.apply(lambda dt: dt.replace(day=1))

Gives:

0   2014-01-01
1   2014-03-01
2   2014-06-01
dtype: datetime64[ns]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...