how to create a new column that is a sum of multiple columns pandas dataframe in python

To create a new column that is a sum of multiple columns in a pandas DataFrame, you can use the "+" operator to add the desired columns together and assign the result to a new column.

Here's an example:

main.py
import pandas as pd

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

df = pd.DataFrame(data)

# Create new column 'D' which is the sum of columns 'A', 'B', and 'C'
df['D'] = df['A'] + df['B'] + df['C']

# Print the updated DataFrame
print(df)
294 chars
15 lines

Output:

main.py
   A  B  C   D
0  1  4  7  12
1  2  5  8  15
2  3  6  9  18
60 chars
5 lines

In this example, we first create a DataFrame with columns A, B, and C. Then, we use the "+" operator to add columns A, B, and C together, and assign the result to a new column 'D' in the DataFrame. Finally, we print the updated DataFrame showing the newly created column 'D'.

related categories

gistlibby LogSnag