mecobalamin’s diary

人間万事塞翁が馬

https://help.hatenablog.com/entry/developer-option

TimedeltaIndexをastypeで変換する

日付の差分をとってヒストグラムを作る

元のデータはこれ

a b
1 2021年1月15日 2021年1月16日
2 2021年1月14日 2021年1月16日
3 2021年1月14日 2021年1月16日
4 2021年1月15日 2021年1月16日
5 2021年1月15日 2021年1月16日
6 2021年1月13日 2021年1月16日

以下続く

aとbの差分を取ると1行目は1日、6行目は3日である

上記のデータがデータフレームdfに入っているとするとき
差分をとって頻度を数えるには以下のようにする

delta = df.iloc[:, 1] -df.iloc[:, 0]
delta = delta.valu_counts().sort_index()

このときdeltaは以下のようになっていて

1 days      798
2 days     1324
3 days      852
4 days      654

型は

print(type(delta))
<class 'pandas.core.series.Series'>

となっている

このままヒストグラムにつかえそうだが
以下のようにするとエラーになる

fig = plt.figure(figsize = (12.0, 9.0))
ax = fig.subplots()
ax.bar(delta.index, delta)

エラーメッセージは以下の通り

TypeError: the dtypes of parameters x (timedelta64[ns]) and width (float64) are incompatible

deltaのindexの型を調べるとTimedeltaIndexになっている

print(type(delta.index))
<class 'pandas.core.indexes.timedeltas.TimedeltaIndex'>

この場合、indexの型を変えるとうまくいった

ax.bar(delta.index.astype('str'), delta)