1

i have data frame as follows and i wanna make a row sum new dataframe and a,b,c,d column values is string.

      name  a         b     c      d 
      aa.   10,000  1,000 1,000  1,000
      bb.   10,000  1,000 1,000  1,000
      cc.   10,000  1,000 1,000  1,000
      dd.   10,000  1,000 1,000  1,000
      ee.   10,000  1,000 1,000  1,000
      ff.   10,000  1,000 1,000  1,000
      gg.   10,000  1,000 1,000  1,000

for example, new row sum dataframe should as belows

  sum   70,000  70,000 70,000  70,000

i tried using df.sumO() but got a object type. but i need is dataframe like sum 70,000 70,000 70,000 70,000

so i question to here. thank you in advance !

jerry han
  • 425
  • 4
  • 15

1 Answers1

1

You can use sum by all columns and then set sum value to last value of name column:

i = len(df)
df.loc[i] = df.sum()
df.loc[i, 'name'] = 'sum'
print (df)
  name   a   b   c   d
0  aa.   1   1   1   1
1  bb.   1   0   0   1
2  cc.   3   4   4   4
3  dd.   2   2   2   2
4  ee.   1   1   1   1
5  ff.   1   1   1   1
6  gg.   1   1   1   1
7  sum  10  10  10  11

EDIT: If possible columns are non numeric, use to_numeric for all columns without first, get sum and add name value to Series, last assign new row:

s = df.iloc[:, 1:].apply(pd.to_numeric, errors='coerce').sum()
s.loc['name'] = 'sum'
df.loc[len(df)] = s

print (df)
  name   a   b   c   d
0  aa.   1   1   1   1
1  bb.   1   0   0   1
2  cc.   3   4   4   4
3  dd.   2   2   2   2
4  ee.   1   1   1   1
5  ff.   1   1   1   1
6  gg.   1   1   1   1
7  sum  10  10  10  11
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252