make a new colmn of a dataframe that is mean of specific columns in a given row in python

To create a new column in a DataFrame that is the mean of specific columns in a given row, you can use the mean function from the pandas library in Python.

Here's an example to demonstrate this:

main.py
import pandas as pd

# Create a sample DataFrame
data = {'A': [10, 20, 30],
        'B': [40, 50, 60],
        'C': [70, 80, 90]}
df = pd.DataFrame(data)

# Calculate the mean of specific columns for each row
df['Mean'] = df[['A', 'B']].mean(axis=1)

# Display the resulting DataFrame
print(df)
295 chars
14 lines

By using the square brackets [], you can specify the column names for which you want to calculate the mean. In the example above, we calculate the mean of columns 'A' and 'B' for each row and assign the result to a new column named 'Mean'. The mean function is applied along the row axis (axis=1).

Output:

main.py
    A   B   C  Mean
0  10  40  70  25.0
1  20  50  80  35.0
2  30  60  90  45.0
80 chars
5 lines

In this case, the 'Mean' column is computed by taking the mean of the 'A' and 'B' columns for each row.

gistlibby LogSnag