Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (50.2k points)

I have a dataframe, something like:

     foo  bar qux

0    a 1    3.14

1    b 3    2.72

2    c 2    1.62

3    d 9    1.41

4    e 3    0.58

and I would like to add a 'total' row to the end of the dataframe:

     foo  bar qux

0    a 1    3.14

1    b 3    2.72

2    c 2    1.62

3    d 9    1.41

4    e 3    0.58

5    tot 15   9.47

I've tried to use the sum command but I end up with a Series, which although I can convert back to a Dataframe, doesn't maintain the data types:

tot_row = pd.DataFrame(df.sum()).T

tot_row['foo'] = 'tot'

tot_row.dtypes:

     foo    object

     bar    object

     qux    object

I would like to maintain the data types from the original data frame as I need to apply other operations to the total row, something like:

baz = 2*tot_row['qux'] + 3*tot_row['bar']

1 Answer

0 votes
by (108k points)

You just have to append a totals row with the following code:

df.append(df.sum(numeric_only=True), ignore_index=True)

If you are interested to learn Pandas visit this Python Pandas Tutorial.

Browse Categories

...