Calculate Average of a Column in CSV using Python

Learn how to read a CSV file and calculate the average of a specific column using Python's pandas library.

By Cojocaru David1h ago (Dec 19, 2025)
csv
data analysis
pandas

Calculate Average of a Column in CSV using Python

python
import pandas as pd

def calculate_average(csv_file, column_name):
    # Read the CSV file into a DataFrame
    df = pd.read_csv(csv_file)
    
    # Check if the column exists in the DataFrame
    if column_name in df.columns:
        # Calculate the average of the specified column
        average = df[column_name].mean()
        return average
    else:
        raise ValueError(f'Column {column_name} does not exist in the CSV file.')

# Example usage
if __name__ == '__main__':
    csv_file = 'data.csv'  # Path to your CSV file
    column_name = 'age'    # Column for which to calculate the average
    try:
        avg = calculate_average(csv_file, column_name)
        print(f'The average of column {column_name} is: {avg}')
    except ValueError as e:
        print(e)

Views

0

Lines

23

Characters

778

Likes

1

Details

Language
Python
Created
Dec 19, 2025
Updated
1h ago
Size
0.8 KB

Build your snippet library

Join thousands of developers organizing and sharing code snippets.