Reorder data frame from calendar year to water yea

2019-08-21 07:14发布

This question has been solved with R, but I haven't seen useful examples with Python. I would like to learn how to convert calendar year (1/1/1990 to 12/31/2010) discharge data to water year data (i.e. 10/01/1990 to 9/31/2010). Thank you for the assistance.

1条回答
唯我独甜
2楼-- · 2019-08-21 07:39

You could use apply and write your own function to create a new column WY:

IF you have have df:

                 Date  Discharge
0 2011-10-01 00:00:00  0.0
1 2011-10-01 01:00:00  0.0
2 2011-10-01 02:00:00  0.0
3 2011-10-01 03:00:00  0.0
4 2011-10-01 04:00:00  0.0

Then:

import pandas as pd

def assign_wy(row):
    if row.Date.month>=10:
        return(pd.datetime(row.Date.year+1,1,1).year)
    else:
        return(pd.datetime(row.Date.year,1,1).year)

df['WY'] = df.apply(lambda x: assign_wy(x), axis=1)
查看更多
登录 后发表回答