Learn how to read a CSV file and calculate the average of a specific column using Python's pandas library.
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
Lines
Characters
Likes