1

For the Pandas dataframe

df

Language    # of Files  Blank Lines Comment Lines   Code Lines
C++            15             66       35                 354
C/C++ Header    1              3       7                   4
Markdown        6              73      0                  142
Python          110          1998     2086                4982
Tcl/Tk          1            14        18                 273
YAML            1             0         6                  20

when I use the code below, it sums each column with NAN for non-integer

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

output

Language    # of Files  Blank Lines Comment Lines   Code Lines
C++            15             66       35                 354
C/C++ Header    1              3       7                   4
Markdown        6              73      0                  142
Python          110          1998     2086                4982
Tcl/Tk          1            14        18                 273
YAML            1             0         6                  20
NAN             134           2154     2152               5775

What should I change in the code to add a string "Total" instead of NAN

Language    # of Files  Blank Lines Comment Lines   Code Lines
C++            15             66       35                 354
C/C++ Header    1              3       7                   4
Markdown        6              73      0                  142
Python          110          1998     2086                4982
Tcl/Tk          1            14        18                 273
YAML            1             0         6                  20
TOTAL           134           2154     2152               5775
Anthon
  • 69,918
  • 32
  • 186
  • 246
Hariom Singh
  • 3,512
  • 6
  • 28
  • 52

2 Answers2

3

You could

In [268]: total = df.sum()

In [269]: total['Language'] = 'Total'

In [270]: df.append(total, ignore_index=True)
Out[270]:
       Language  # of Files  Blank Lines  Comment Lines  Code Lines
0           C++          15           66             35         354
1  C/C++ Header           1            3              7           4
2      Markdown           6           73              0         142
3        Python         110         1998           2086        4982
4        Tcl/Tk           1           14             18         273
5          YAML           1            0              6          20
6         Total         134         2154           2152        5775
Zero
  • 74,117
  • 18
  • 147
  • 154
  • [`df.append` is deprecated since 1.4](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html) – ggorlen Jan 29 '23 at 03:09
1

Here is another version:

df.loc[len(df)] = np.insert('Total', 1, df.drop('Language', axis=1).sum(0))
Anton vBR
  • 18,287
  • 5
  • 40
  • 46