row-wise summation of a pandas dataframe in python

To perform a row-wise summation of a Pandas DataFrame in Python, you can use the sum() function along with the axis parameter set to 1.

Here's an example of how you can do it:

main.py
import pandas as pd

# Create a sample DataFrame
data = {'A': [1, 2, 3],
        'B': [4, 5, 6],
        'C': [7, 8, 9]}
df = pd.DataFrame(data)

# Calculate row-wise summation
row_sum = df.sum(axis=1)

# Print the result
print(row_sum)
237 chars
14 lines

Output:

main.py
0    12
1    15
2    18
dtype: int64
37 chars
5 lines

In the above example, we create a sample DataFrame df with three columns A, B, and C. We then use the sum() function with axis=1 to perform the row-wise summation and store the result in the row_sum variable. Finally, we print the row_sum to display the row-wise summation of the DataFrame.

Note that the result is a Pandas Series object with row indices as 0, 1, and 2, corresponding to the rows of the DataFrame.

related categories

gistlibby LogSnag