[英]How to convert Index column with name 'Date' to weekday name in dataframe. The index format is dtype: int64
[英]How to convert index column of int64 type to hour in matplotlib xticks
我想 plot matplotlib
條形圖與數據:
value
Hour
0 100
1 200
2 100
3 200
4 100
5 200
6 200
7 200
8 100
9 200
10 100
11 100
12 200
13 100
14 100
15 200
16 100
17 200
18 100
19 100
20 100
21 200
22 100
23 200
它返回帶有整數1 to 23
作為xticks
的圖形。 預計 output 將xticks
更改為時間格式,即hour:minute
,例如01:00
、 02:00
等... Hour
為int64
類型。
圖表代碼:
fig, ax = plt.subplots(figsize=(30,10))
plt.xticks(np.arange(0, 24), fontsize=30)
plt.bar(x.index, x.value, color = 'c')
# x.index = pd.to_datetime(x.index, format='%H').strftime('%H')
# ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M'))
# x.index = [datetime.time(i, 0) for i in x.index]
ax.get_yaxis().set_major_formatter(
ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
plt.xlabel('Hour', fontsize=35)
plt.ylabel('Value', fontsize=35)
我嘗試將索引列Hour
轉換為 Time(hour) 格式:
x.index = pd.to_datetime(x.index, format='%H').strftime('%H')
捕獲錯誤:
TypeError: the dtypes of parameters x (object) and width (float64) are incompatible
還根據其他類似問題嘗試ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M'))
和x.index = [datetime.time(i, 0) for i in x.index]
但沒有奏效.
為什么它不起作用? 是因為索引形式還是我沒有將Hour
列從int64
正確更改為time
?
你可以試試這個。 使用pd.Index.astype
pd.to_datetime(df.index.astype('object'),format='%H').strftime('%H:%M')
Index(['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00',
'08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00',
'16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'],
dtype='object', name='Hour')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.