4
3

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 3 years have passed since last update.

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

Posted at

下記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
4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?