LoginSignup
3

More than 1 year has passed since last update.

posted at

【Python】PandasのDataFrameに合計行を追加する

下記2つのいずれかがおすすめ。

def append_sum_row(df):
    return df.append(df.sum(numeric_only=True), ignore_index=True)
def append_sum_row_label(df):
    df.loc['Total'] = df.sum(numeric_only=True)
    return df

サンプル

それぞれを使ってみると下記のようになります。
行ラベル(index)の使用の有無によって使い分けると良いと思います。

sample
import pandas as pd


def append_sum_row(df):
    return df.append(df.sum(numeric_only=True), ignore_index=True)

def append_sum_row_label(df):
    df.loc['Total'] = df.sum(numeric_only=True)
    return df

data_frame = pd.DataFrame([
    ["A", 100, 200],
    ["B", 300, 400],
    ["C", 500, 600]
])

print("append_sum_row:", append_sum_row(data_frame), sep="\n")
print("append_sum_row_label:", append_sum_row_label(data_frame), sep="\n")
print
append_sum_row:
     0      1       2
0    A  100.0   200.0
1    B  300.0   400.0
2    C  500.0   600.0
3  NaN  900.0  1200.0

append_sum_row_label:
         0      1       2
0        A  100.0   200.0
1        B  300.0   400.0
2        C  500.0   600.0
Total  NaN  900.0  1200.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
What you can do with signing up
3