88 lines
2.6 KiB
Python
88 lines
2.6 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Data Analysis Script
|
|
"""
|
|
import pandas as pd
|
|
import numpy as np
|
|
import argparse
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def load_data(filepath: str) -> pd.DataFrame:
|
|
"""Load data from CSV, Excel, or JSON file."""
|
|
path = Path(filepath)
|
|
suffix = path.suffix.lower()
|
|
if suffix == '.csv':
|
|
return pd.read_csv(filepath)
|
|
elif suffix in ['.xlsx', '.xls']:
|
|
return pd.read_excel(filepath)
|
|
elif suffix == '.json':
|
|
return pd.read_json(filepath)
|
|
else:
|
|
raise ValueError(f"Unsupported file format: {suffix}")
|
|
|
|
|
|
def explore_data(df: pd.DataFrame) -> None:
|
|
"""Print basic data exploration info."""
|
|
print("=== Data Overview ===")
|
|
print(f"Shape: {df.shape}")
|
|
print(f"\nColumns: {list(df.columns)}")
|
|
print(f"\nDtypes:\n{df.dtypes}")
|
|
print(f"\nMissing values:\n{df.isnull().sum()}")
|
|
print(f"\nBasic stats:\n{df.describe()}")
|
|
|
|
|
|
def clean_data(df: pd.DataFrame) -> pd.DataFrame:
|
|
"""Basic data cleaning."""
|
|
df = df.drop_duplicates()
|
|
df = df.dropna(axis=1, how='all')
|
|
return df
|
|
|
|
|
|
def analyze_data(df: pd.DataFrame) -> dict:
|
|
"""Perform basic analysis."""
|
|
numeric_cols = df.select_dtypes(include=[np.number]).columns
|
|
results = {
|
|
'correlations': df[numeric_cols].corr().to_dict() if len(numeric_cols) > 1 else {},
|
|
'summary_stats': df[numeric_cols].describe().to_dict() if len(numeric_cols) > 0 else {},
|
|
}
|
|
return results
|
|
|
|
|
|
def save_results(results: dict, output_path: str) -> None:
|
|
"""Save analysis results to JSON."""
|
|
import json
|
|
with open(output_path, 'w') as f:
|
|
json.dump(results, f, indent=2, default=str)
|
|
print(f"Results saved to {output_path}")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="Data Analysis Script")
|
|
parser.add_argument('input_file', help='Path to input data file (CSV, Excel, JSON)')
|
|
parser.add_argument('-o', '--output', default='analysis_results.json',
|
|
help='Output file for results (default: analysis_results.json)')
|
|
parser.add_argument('--explore', action='store_true',
|
|
help='Show data exploration info')
|
|
args = parser.parse_args()
|
|
|
|
try:
|
|
df = load_data(args.input_file)
|
|
print(f"Loaded {df.shape[0]} rows, {df.shape[1]} columns")
|
|
|
|
if args.explore:
|
|
explore_data(df)
|
|
|
|
df = clean_data(df)
|
|
results = analyze_data(df)
|
|
save_results(results, args.output)
|
|
|
|
print("Analysis complete!")
|
|
except Exception as e:
|
|
print(f"Error: {e}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main() |