I have a data frame:
date value
0 2017-11-30 13:58:57 901
1 2017-11-30 13:59:41 905
2 2017-11-30 13:59:41 925
That was generated by:
import pandas as pd
df = pd.DataFrame.from_items( [('date', ['2017-11-30 13:58:57', '2017-11-30 13:59:41', '2017-11-30 13:59:41']),("value", [901, 905, 925])])
df['date'] = pd.to_datetime(df['date'])
I want to calculate the percentage change between two consecutive rows, but when I use:
df.pct_change()
I get the error:
ufunc true_divide cannot use operands with types dtype('<M8[ns]') and dtype('<M8[ns]')
How do I make it ignore the date column?
How do I make it ignore the date column?
Here's a solution with select_dtypes
that should generalise to any dataframe by ignoring non-numeric columns -
df.select_dtypes(include=['number']).pct_change()
value
0 NaN
1 0.004440
2 0.022099
我会尝试指定值列。
df[‘pctcng’]=df[‘value’].pct_change()
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.