如何修复TypeError:仅对DatetimeIndex

时间:2019-08-27 13:58:01

标签: python pandas datetimeindex

我试图用matplotlib制作烛台。有这样的csv文件。

,CloseTime  ,OpenPrice,HighPrice, LowPrice, ClosePrice, Volume,    Adj Volume
0,1523836800,503.0,    535.01184,497.09033, 533.72046,  13180.739, 6791510.5
1,1523923200,533.72046,538.0,    498.31665, 511.78436,  9553.387,  4888143.5
2,1524009600,512.1794, 521.491,  500.9132,  503.0,      5921.6836, 3020385.5
3,1524096000,502.0,    527.3317, 502.0,     524.60547,  8402.214,  4344271.5
4,1524182400,526.1176, 570.1495, 519.5058,  568.43866,  10088.153, 5501865.0

我的代码在下面

import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd

df=pd.read_csv('eth.csv', parse_dates=True,index_col=0)
df_ohcl=df['ClosePrice'].resample('10D').ohlc()
df_volume=df['Volume'].resample('10D').sum()
print(df_ohcl())```

when i run program i get an answer like 
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Int64Index'

how can i fix this.thanks for helping me

1 个答案:

答案 0 :(得分:0)

创建DatetimeIndex-首先使用to_datetimeCloseTime参数将unit转换为日期时间,然后使用DataFrame.set_index

df.columns = df.columns.str.strip()

df['CloseTime'] = pd.to_datetime(df['CloseTime'], unit='s')
df = df.set_index('CloseTime')
print (df)
             OpenPrice  HighPrice   LowPrice   ClosePrice      Volume  \
CloseTime                                                               
2018-04-16   503.00000  535.01184  497.09033    533.72046  13180.7390   
2018-04-17   533.72046  538.00000  498.31665    511.78436   9553.3870   
2018-04-18   512.17940  521.49100  500.91320    503.00000   5921.6836   
2018-04-19   502.00000  527.33170  502.00000    524.60547   8402.2140   
2018-04-20   526.11760  570.14950  519.50580    568.43866  10088.1530   

                 Adj Volume  
CloseTime                    
2018-04-16        6791510.5  
2018-04-17        4888143.5  
2018-04-18        3020385.5  
2018-04-19        4344271.5  
2018-04-20        5501865.0