how to take mean of different columns for a given row in python

To take the mean of different columns for a given row in Python, you can use the numpy library. Here's an example of how you can do it:

main.py
import numpy as np

# Define your data as a 2D array or list of lists
data = [[1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12]]

# Define the index of the row you want to calculate the mean for
row_index = 1

# Calculate the mean of the specified row using np.mean and axis=1
mean_values = np.mean(data[row_index])

# Print the mean values
print(mean_values)
370 chars
16 lines

In this example, we have a 2D array data representing a table with rows and columns. We specify the row_index variable to indicate which row we want to calculate the mean for. Then, np.mean calculates the mean of the specified row using axis=1, which means we want to calculate the mean across columns.

Note that np.mean returns a single value or an array of mean values if you have multiple rows. In this case, since we only have one row, mean_values will contain the mean value(s) for the specified row.

related categories

gistlibby LogSnag