1
0

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 1 year has passed since last update.

[Python]Dataframeで簡単に行の変化率を計算する

Posted at

はじめに

広告のクリック回数の週ごとの変化率を見るとします。

import pandas as pd

import pandas as pd

data = {'date': ['2022-12-01', '2022-12-08', '2022-12-15', '2022-12-22', '2022-12-29'],
        'ad_clicks': [10000, 15000, 20000, 17000, 18000]}
df = pd.DataFrame(data)
df['date'] = pd.to_datetime(df['date'])
date ad_clicks
0 2022-12-01 10000
1 2022-12-08 15000
2 2022-12-15 20000
3 2022-12-22 17000
4 2022-12-29 18000

一週間前のデータ列を作る

ここでdfのshiftメソッドを使います!

df['ad_clicks_prev_week'] = df['ad_clicks'].shift()
date ad_clicks ad_clicks_prev_week
0 2022-12-01 10000 NaN
1 2022-12-08 15000 10000.0
2 2022-12-15 20000 15000.0
3 2022-12-22 17000 20000.0
4 2022-12-29 18000 17000.0

実行するとad_clicksのずらした結果をclicks_prev_weekに格納できました。

※もし二週間ごと計算したい場合は、shift(2)でできます。

変化率を計算する

df['ad_click_rate'] = ((df['ad_clicks'] - df['ad_clicks_prev_week']) / df['ad_clicks_prev_week'])
date ad_clicks ad_clicks_prev_week ad_click_rate
0 2022-12-01 10000 NaN NaN
1 2022-12-08 15000 10000.0 0.500000
2 2022-12-15 20000 15000.0 0.333333
3 2022-12-22 17000 20000.0 -0.150000
4 2022-12-29 18000 17000.0 0.058824

変化率をパーセント(%)で表示する

df['ad_click_rate'] = df['ad_click_rate'].apply(lambda x: '{:.2%}'.format(x))
date ad_clicks ad_clicks_prev_week ad_click_rate
0 2022-12-01 10000 NaN NaN
1 2022-12-08 15000 10000.0 50.00%
2 2022-12-15 20000 15000.0 33.33%
3 2022-12-22 17000 20000.0 -15.00%
4 2022-12-29 18000 17000.0 5.88%

これで簡単に行ごとの変化率が計算できます!
ぜひ試してみてください〜

1
0
2

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?