With the default axis=0, sum() adds down each column, producing one total per column as a Series; axis=1 instead sums across each row. By default, skipna=True means NaN values are treated as if they weren't there at all rather than making the whole sum NaN — summing a column containing a NaN alongside real numbers still produces a real number, not NaN, which is usually the desired behavior for real-world data with gaps, but worth knowing explicitly since it's a silent, automatic choice.
1Understanding df.sum()
With the default axis=0, sum() adds down each column, producing one total per column as a Series; axis=1 instead sums across each row. By default, skipna=True means NaN values are treated as if they weren't there at all rather than making the whole sum NaN — summing a column containing a NaN alongside real numbers still produces a real number, not NaN, which is usually the desired behavior for real-world data with gaps, but worth knowing explicitly since it's a silent, automatic choice.
sum()'s default of skipna=True silently ignores NaN values rather than propagating them into the result — if you specifically need to know whether any missing data affected the calculation, check for NaN separately rather than relying on sum() to signal it.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 30]})
print(df.sum())2Practical Example
Here is a real-world application of df.sum() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"team": ["A", "A", "B"], "score": [10, 20, 30]})
print(df.groupby("team")["score"].sum())3Best Practices
Follow these guidelines when working with df.sum():
1. Chain sum() after groupby() for per-group totals, the pandas equivalent of a SQL GROUP BY with SUM()
2. Be aware of skipna's default of True — NaN values are silently excluded from the sum rather than causing the whole result to become NaN
3. Specify axis explicitly, 0 for column sums, 1 for row sums, rather than relying on remembering the default
Tip: sum()'s default of skipna=True silently ignores NaN values rather than propagating them into the result — if you specifically need to know whether any missing data affected the calculation, check for NaN separately rather than relying on sum() to signal it.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 30]})
print(df.sum())