How to add a yearly amount to daily data in Pandas -


i have 2 dataframes in pandas. 1 of them has data every month, other 1 has data every year. need computation yearly value added monthly value.

something this:

df1, monthly:

    2013-01-01         1     2013-02-01         1             ...     2014-01-01         1     2014-02-01         1             ...     2015-01-01         1 

df2, yearly:

    2013-01-01         1     2014-01-01         2     2015-01-01         3 

and want produce this:

    2013-01-01         (1+1) = 2     2013-02-01         (1+1) = 2             ...     2014-01-01         (1+2) = 3     2014-02-01         (1+2) = 3             ...     2015-01-01         (1+3) = 4 

where value of monthly data added value of yearly data depending on year (first value in parenthesis monthly data, second value yearly data).

assuming "month" column called date in dataframe df, can obtain year using dt member:

pd.to_datetime(df.date).dt.year 

add column month dataframe, , call year. (see this explanation).

now same year dataframe.

do merge on month , year dataframes, specifying how=left.

in resulting dataframe, have both columns. add them.


example

month_df = pd.dataframe({     'date': ['2013-01-01', '2013-02-01', '2014-02-01'],     'amount': [1, 2, 3]}) year_df = pd.dataframe({     'date': ['2013-01-01', '2014-02-01', '2015-01-01'],     'amount': [7, 8, 9]})  month_df['year'] = pd.to_datetime(month_df.date).dt.year year_df['year'] = pd.to_datetime(year_df.date).dt.year  >>> pd.merge(     month_df,      year_df,      left_on='year',      right_on='year',     how='left')     amount_x    date_x  year    amount_y    date_y 0   1   2013-01-01  2013    7   2013-01-01 1   2   2013-02-01  2013    7   2013-01-01 2   3   2014-02-01  2014    8   2014-02-01 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -