Pandas備忘録

インデックスの変更

             A     B day_of_the_week
2018/1/1   1.2  13.5             Mon
2018/1/10  2.5  12.1             Wed
2018/1/15  1.4  10.9             Mon
2018/1/22  3.2  11.5             Mon
2018/2/5   1.8  10.6             Mon
2018/2/12  2.2  10.1             Mon
2018/2/19  2.8  11.7             Mon
2018/2/26  3.4  12.5             Mon
2018/3/5   1.9  10.0             Mon
2018/3/12  2.0  11.0             Mon
              A      B day_of_the_week
2018-01-01  1.2  13.50             Mon
2018-01-08  1.3  12.20             Mon
2018-01-15  1.4  10.90             Mon
2018-01-22  3.2  11.50             Mon
2018-01-29  2.5  11.05             Mon
2018-02-05  1.8  10.60             Mon
2018-02-12  2.2  10.10             Mon
2018-02-19  2.8  11.70             Mon
2018-02-26  3.4  12.50             Mon
2018-03-05  1.9  10.00             Mon
2018-03-12  2.0  11.00             Mon

上のデータフレームを下のように変更する方法。

  • 月曜日だけを抽出
  • 毎週のデータにするため存在しないindexを追加(この場合1/8と1/29)
  • 存在しないデータを補間
import pandas as pd
df = pd.read_csv('Book1.csv', index_col=0)
df = df.reindex(pd.to_datetime(df.index))

new_index = pd.date_range(start=df.index[0], end=df.index[-1], freq='7D')
df = df.reindex(new_index)
df.interpolate(limit_area='inside',inplace=True)
df['day_of_the_week']='Mon'

結合して保存

import pandas as pd

df_data = pd.read_csv('Pt1_data.csv', index_col=0)
df_data = df_data.reindex(pd.to_datetime(df_data.index))

df_drug = pd.read_csv('Pt1_drug.csv', index_col=0)
df_drug = df_drug.reindex(pd.to_datetime(df_drug.index))

new_index = pd.date_range(start=df_data.index[0], end=df_data.index[-1], freq='7D')

df_data = df_data.reindex(new_index)
df_drug = df_drug.reindex(new_index)

df = pd.concat([df_data, df_drug], axis=1)

df.interpolate(limit_direction='both', inplace=True)

df.to_csv('Pt_all.csv')

ある特定の列を1行ずらして1行目を削除する

df['Fe']=df['Fe'].shift()
df = df.drop(df.index[0])