Calculating Mean of Column 'A' for Each Group in Column 'B Using Pandas Groupby'

Here is a Python script to solve the problem:

import pandas as pd

# Load data into DataFrame
df = pd.DataFrame({
    'A': ['24', '12', '21', '11', '13', '14', '22', '23'],
    'B': [7, 8, 1, 3, 4, 5, 6, 7]
})

# Convert column A to numeric values
df['A'] = pd.to_numeric(df['A'])

# Calculate the mean of column A for each group in column B
grouped = df.groupby('B')['A'].mean()

# Print the result
print(grouped)

When you run this script, it will calculate and print the mean value of column ‘A’ for each unique value in column ‘B’.

The output:

B
1    3.5
2   12.0
3   21.0
4   11.0
5    7.5
6    5.5
Name: A, dtype: float64

Last modified on 2023-08-07