DataFrame.sum() - ( Pandas DataFrame Basics )
Heading h2
Syntax
DataFrame.sum(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
Example
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
# summing all columns
total_sum = df.sum()
# summing all rows
row_sum = df.sum(axis=1)
print(total_sum)
print(row_sum)
Output
A 6
B 15
C 24
dtype: int64
0 12
1 15
2 18
dtype: int64
Explanation
Pandas is a popular library used for data analysis in Python. The DataFrame
class in pandas is used for working with tabular data.
The DataFrame.sum()
method is used to get the sum of values in a pandas DataFrame. It takes several optional parameters for specifying the axis, whether to skip NaN values, etc.
In the above example, we create a simple DataFrame with three columns and three rows. We then use the sum()
method to calculate the sum of values in each column and each row. The total_sum
variable contains the sums of the columns, while the row_sum
variable contains the sums of the rows.
Use
The DataFrame.sum()
method is useful for calculating the sum of values in a pandas DataFrame, both for individual columns or for entire rows.
Important Points
- The
DataFrame.sum()
method is used to get the sum of values in a pandas DataFrame - It takes several optional parameters for specifying the axis, whether to skip NaN values, etc.
- The method returns either the sum of the columns or the sum of each row, depending on the specified axis
- NaN values are treated as 0 unless explicitly skipped
Summary
In conclusion, the DataFrame.sum()
method is a useful function in pandas for calculating the sum of values in a DataFrame. It can be customized with several optional parameters for specifying the axis, whether to skip NaN values, etc. It returns either the sum of the columns or the sum of each row, depending on the specified axis, and NaN values are treated as 0 unless explicitly skipped.