【Pandas】累積和と累積積を求める方法、さらに累積平均値を求める方法[Python]

  • URLをコピーしました!

Pandas

前回、Pandasで行データを追加する際に出るエラー「IndexError: iloc cannot enlarge its target object」の対処法を紹介しました。

今回はPandasで各行までの累積和と累積積を求める方法、さらにその各行までの累積平均値を求める方法を紹介します。

それでは始めていきましょう。

累積和を求める方法

各行までの累積和を求めるには「データフレーム.cumsum()」を用います。

import pandas as pd

data = {"A":[1.0, 2.0, 3.0, 4.0, 5.0],
        "B":[2.0, 4.0, 6.0, 8.0, 10.0],
        "C":[3.0, 6.0, 9.0, 12.0, 15.0]}

df = pd.DataFrame(data)

df = df.cumsum()

print(df)

実行結果
      A     B     C
0   1.0   2.0   3.0
1   3.0   6.0   9.0
2   6.0  12.0  18.0
3  10.0  20.0  30.0
4  15.0  30.0  45.0

また「axis=累積する軸方向」を追加すると他の軸方向に対して累積和を計算することができます。

import pandas as pd

data = {"A":[1.0, 2.0, 3.0, 4.0, 5.0],
        "B":[2.0, 4.0, 6.0, 8.0, 10.0],
        "C":[3.0, 6.0, 9.0, 12.0, 15.0]}

df = pd.DataFrame(data)

df = df.cumsum(axis=1)

print(df)

実行結果
     A     B     C
0  1.0   3.0   6.0
1  2.0   6.0  12.0
2  3.0   9.0  18.0
3  4.0  12.0  24.0
4  5.0  15.0  30.0

累積積を求める方法

各行までの累積和を求めるには「データフレーム.cumprod()」を用います。

import pandas as pd

data = {"A":[1.0, 2.0, 3.0, 4.0, 5.0],
        "B":[2.0, 4.0, 6.0, 8.0, 10.0],
        "C":[3.0, 6.0, 9.0, 12.0, 15.0]}

df = pd.DataFrame(data)

df = df.cumprod()

print(df)

実行結果
       A       B        C
0    1.0     2.0      3.0
1    2.0     8.0     18.0
2    6.0    48.0    162.0
3   24.0   384.0   1944.0
4  120.0  3840.0  29160.0

こちらも「axis=累積する軸方向」を追加すると他の軸方向に対して累積積を計算することができます。

import pandas as pd

data = {"A":[1.0, 2.0, 3.0, 4.0, 5.0],
        "B":[2.0, 4.0, 6.0, 8.0, 10.0],
        "C":[3.0, 6.0, 9.0, 12.0, 15.0]}

df = pd.DataFrame(data)

df = df.cumprod(axis=1)

print(df)

実行結果
     A     B      C
0  1.0   2.0    6.0
1  2.0   8.0   48.0
2  3.0  18.0  162.0
3  4.0  32.0  384.0
4  5.0  50.0  750.0

累積平均を求める方法

累積平均を求めるにはまず「データフレーム.cumsum()」で累積和を計算し、その値を「インデックス+1」で割ることで求めることができます。

import pandas as pd

data = {"A":[1.0, 2.0, 3.0, 4.0, 5.0],
        "B":[2.0, 4.0, 6.0, 8.0, 10.0],
        "C":[3.0, 6.0, 9.0, 12.0, 15.0]}

df = pd.DataFrame(data)

df = df.cumsum()

for row in range(len(df.index)):
    df.iloc[row] = df.iloc[row]/(row+1)

print(df)

実行結果
     A    B    C
0  1.0  2.0  3.0
1  1.5  3.0  4.5
2  2.0  4.0  6.0
3  2.5  5.0  7.5
4  3.0  6.0  9.0

ちなみに上記の方法ではデータを書き換えていますので、累積平均がfloat型になる場合、最初のデータもfloat型にしておかないと「FutureWarning: Setting an item of incompatible dtype is deprecated and will raise an error in a future version of pandas. Value ‘X.X’ has dtype incompatible with int64, please explicitly cast to a compatible dtype first.」がでることに注意してください。

import pandas as pd

data = {"A":[1, 2, 3, 4, 5],
        "B":[2, 4, 6, 8, 10],
        "C":[3, 6, 9, 12, 15]}

df = pd.DataFrame(data)

df = df.cumsum()

for row in range(len(df.index)):
    df.iloc[row] = df.iloc[row]/(row+1)

print(df)

実行結果
     A  B    C
0  1.0  2  3.0
1  1.5  3  4.5
2  2.0  4  6.0
3  2.5  5  7.5
4  3.0  6  9.0
/var/folders/sp/hg7p80kx22s7vct7yb0zl5cm0000gn/T/ipykernel_6262/
4158105694.py:12: FutureWarning: Setting an item of incompatible 
dtype is deprecated and will raise an error in a future version of 
pandas. Value '1.5' has dtype incompatible with int64, please 
explicitly cast to a compatible dtype first.
  df.iloc[row] = df.iloc[row]/(row+1)
/var/folders/sp/hg7p80kx22s7vct7yb0zl5cm0000gn/T/ipykernel_6262/
4158105694.py:12: FutureWarning: Setting an item of incompatible 
dtype is deprecated and will raise an error in a future version of 
pandas. Value '4.5' has dtype incompatible with int64, please 
explicitly cast to a compatible dtype first.
  df.iloc[row] = df.iloc[row]/(row+1)

そのため別のデータフレームを用意して、計算値を移し替える方が安全かもしれません。

import pandas as pd
import numpy as np

data = {"A":[1, 2, 3, 4, 5],
        "B":[2, 4, 6, 8, 10],
        "C":[3, 6, 9, 12, 15]}

df = pd.DataFrame(data)

df = df.cumsum()

df_new = pd.DataFrame(np.zeros(df.shape))
for row in range(len(df.index)):
    df_new.iloc[row] = df.iloc[row]/(row+1)

print(df_new)

実行結果
     0    1    2
0  1.0  2.0  3.0
1  1.5  3.0  4.5
2  2.0  4.0  6.0
3  2.5  5.0  7.5
4  3.0  6.0  9.0

次回はJupyter NotebookのブラウザをGoogle Choromeに変更する方法を紹介します。

ではでは今回はこんな感じで。

よかったらシェアしてね!
  • URLをコピーしました!

コメント

コメントする