简体   繁体   中英

How to find percent increase/decrease with datetime values in Python?

I have attached a photo of how the data is formatted when I print the df in Jupyter, please check that for reference. Set the DATE column as the index, checked the data type of the index, and converted the index to be a datetime index.

import pandas as pd
df = pd.read_csv ('UMTMVS.csv',index_col='DATE',parse_dates=True)
df.index = pd.to_datetime(df.index)

I need to print out percent increase in value from Month/Year to Month/Year and percent decrease in value from Month/Year to Month/Year.

dataframe format picture

The first correction pertains to how to read your DataFrame.

Passing parse_dates you should define a list of columns to be parsed as dates. So this instruction should be changed to:

df = pd.read_csv('UMTMVS.csv', index_col='DATE', parse_dates=['DATE'])

and then the second instruction in not needed.

To find the percent change in UMTMVS column, use: df.UMTMVS.pct_change() . For your data the result is:

DATE
1992-01-01         NaN
1992-02-01    0.110968
1992-03-01    0.073036
1992-04-01   -0.040080
1992-05-01    0.014875
1992-06-01   -0.330455
1992-07-01    0.368293
1992-08-01    0.078386
1992-09-01    0.082884
1992-10-01   -0.030528
1992-11-01   -0.027791
Name: UMTMVS, dtype: float64

Maybe you should multiply it by 100 , to get true percents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM