This post is also available in: English-US (英語)
python, pandasを使っていて、マルチインデックスのインデックスにある timedelta64[ns] 形式の日にちを引き算して、int型で出力するサンプルコードを書いています。
他に色々方法はあると思いますが、とりあえず、個人的なメモとして残しています。
import pandas as pd
# サンプルデータ
data = [
[1,'2023-03-28','7508'],
[1,'2023-03-30','7600'],
[2,'2023-06-18','9568'],
[2,'2023-06-30','9586'],
[3,'2023-07-10','7507'],
[3,'2023-07-20','7520'],
]
# データフレームの作成
df = pd.DataFrame(data=data, columns=['id','date','val'])
print(df)
"""
id date val
0 1 2023-03-28 7508
1 1 2023-03-30 7600
2 2 2023-06-18 9568
3 2 2023-06-30 9586
4 3 2023-07-10 7507
5 3 2023-07-20 7520
"""
# timedelta64[ns]に変換
print(df['date'].dtypes) # object
df['date'] = pd.to_datetime(df['date'])
print(df['date'].dtypes) # datetime64[ns]
# マルチインデックスの作成
df_mulindex = df.set_index(['id','date'])
print(df_mulindex)
"""
val
id date
1 2023-03-28 7508
2023-03-30 7600
2 2023-06-18 9568
2023-06-30 9586
3 2023-07-10 7507
2023-07-20 7520
"""
# マルチインデックス中のtimedelta64[ns]の日にちを引き算してint型でアウトプット
print(df_mulindex.groupby('id').apply(lambda x: x.index[1][1]-x.index[0][1]).dt.days) # timedelta64[ns] to int
"""
id
1 2
2 12
3 10
dtype: int64
"""




