Reorder data frame from calendar year to water year using Python

本秂侑毒 提交于 2020-01-06 07:23:26

问题


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:


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)


来源:https://stackoverflow.com/questions/52105804/reorder-data-frame-from-calendar-year-to-water-year-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!