One of the following two is recommended.
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
If you try using each, it will be as follows. I think it is better to use it properly depending on whether or not the row label (index) is used.
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
Recommended Posts