📜  pandas row sum - Python (1)

📅  最后修改于: 2023-12-03 15:03:28.522000             🧑  作者: Mango

pandas row sum - Python

Pandas is a widely used data analysis library in Python. It provides various tools for data manipulation, cleaning, and exploration. One of the most common operations is to calculate row sums in a Pandas DataFrame.

Calculating row sums

To calculate row sums in a Pandas DataFrame, we can use the sum() method along the axis of the rows (axis=1). Here is an example:

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({'col1':[1, 2, 3], 'col2':[4, 5, 6]})

# Calculate row sums
df['row_sum'] = df.sum(axis=1)

# Print the updated DataFrame
print(df)

This will output:

   col1  col2  row_sum
0     1     4        5
1     2     5        7
2     3     6        9 

In this example, we first create a sample DataFrame with two columns (col1 and col2). We then calculate the row sums of the DataFrame using the sum() method and passing axis=1 as an argument. We assign the resulting values to a new column called row_sum.

Conclusion

Calculating row sums in a Pandas DataFrame is a common operation in data analysis. Using the sum() method along the axis of the rows (axis=1) is an easy and efficient way to accomplish this task.