2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pandasで欠損値を含んだ日付ごとのデータの累計値を算出する

Last updated at Posted at 2019-03-24

こんな感じでできました。

import pandas as pd

# 実験用データ
df = pd.DataFrame({'date': ['2019-01-05', '2019-01-18', '2019-01-25', '2019-02-06', '2019-02-16', '2019-03-02'],
                   'value': [10, 20, 30, 40, 50, 60],
                   'name': ['', '', '', '', '', '']})

# 日付列を日付型に変える
df['date'] = pd.to_datetime(df['date'])
# 日付リストのDataFrameを作ってマージする。
df = pd.merge(pd.DataFrame({"date": pd.date_range('2019-1-1', '2019-3-31')}), df, how='left')
# 累計値を新たな列として追加
df['cumsum'] = df['value'].fillna(0).cumsum()

print(df)
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?