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
397 views
in Technique[技术] by (71.8m points)

pandas - Is there a way in python dataframe to populate customise week number from a range of dates?

For example, a date range between 1Apr2019 to 31Mar2020. Week 1: 1-7apr2019 Week 2: 8-15apr2019 and so on.

Is there a way to populate the week number in this manner?

Thanks

question from:https://stackoverflow.com/questions/65896502/is-there-a-way-in-python-dataframe-to-populate-customise-week-number-from-a-rang

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

1 Reply

0 votes
by (71.8m points)

use strftime to set the DateTime format, and transform the data you wanted.

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

begin_date, end_date = '1Apr2019', '31Mar2020'
df = pd.DataFrame([
    pd.date_range(begin_date, end_date).strftime('%G-%V'),
    pd.date_range(begin_date, end_date).strftime('%d%b%Y')]).T

group_map = pd.DataFrame(enumerate(df[0].unique())).set_index(1)[0].to_dict()
df['group'] = df[0].map(group_map)
df['week_group'] = (df['group'] + 1).map(lambda x: f'Week {x}')

print(df.head(14))

              0          1  group week_group
    0   2019-13  01Apr2019      0     Week 1
    1   2019-13  02Apr2019      0     Week 1
    2   2019-13  03Apr2019      0     Week 1
    3   2019-13  04Apr2019      0     Week 1
    4   2019-13  05Apr2019      0     Week 1
    5   2019-13  06Apr2019      0     Week 1
    6   2019-13  07Apr2019      0     Week 1
    7   2019-14  08Apr2019      1     Week 2
    8   2019-14  09Apr2019      1     Week 2
    9   2019-14  10Apr2019      1     Week 2
    10  2019-14  11Apr2019      1     Week 2
    11  2019-14  12Apr2019      1     Week 2
    12  2019-14  13Apr2019      1     Week 2
    13  2019-14  14Apr2019      1     Week 2

where:

%G
    ISO 8601 year with century representing the year that contains the greater part of the ISO week (%V).

%V
    ISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4.

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

...