[Python] How do I rename My Excel's Column in Matplotlib? [df.rename does not work for some...

Discussão em 'Python' iniciado por Stack, Fevereiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    In this code, I want to rename the excel column to a shorter column without changing the column name in the excel or expected_columns. The columns are long because they are neccesary survey questions. I could rename it, but when I did, it also showed the same error

    df = pd.read_excel(file_path, engine='openpyxl') if file_path.endswith('.xlsx') else pd.read_csv(file_path)

    # Clean column names to prevent whitespace mismatches
    df.columns = df.columns.str.strip().str.lower().str.replace(r'\s+', '_', regex=True)

    # Define expected columns (after cleaning)
    expected_columns = [
    "how_would_such_inconsistencies_make_you_feel?",
    "how_would_such_logical_error_make_you_feel?",
    "how_would_such_false/misleading_output_make_you_feel?",
    "how_would_such_design_make_you_feel?"
    ]

    # Attempt to find closest matches if exact names are missing
    valid_columns = [col for col in df.columns if any(exp in col for exp in expected_columns)]

    if not valid_columns:
    print("Warning: None of the expected columns were found! Please check column names.")
    return

    sentiment_scores_df = df[valid_columns]
    sentiment_scores = {col: sentiment_scores_df[col].dropna().astype(int).tolist() for col in valid_columns}

    sentiment_counts = {section: Counter(scores) for section, scores in sentiment_scores.items()}

    output_dir = r"C:\Users\ASUS\OneDrive - Sampoerna University\Documents\HTML CSS JAVASCRIPT\Human Computer Interaction\Dashboard\Matplotlib\Images"
    os.makedirs(output_dir, exist_ok=True) # Ensure the folder exists


    I tried using df.rename but it did not work. If anyone can help me, please respond to me.

    Continue reading...

Compartilhe esta Página