[Python] Issue with Number Formatting When Converting CSV to Excel Using Pandas

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

  1. Stack

    Stack Membro Participativo

    I'm having trouble with a Python script that converts CSV files to Excel format using pandas. The issue is that numbers in scientific notation in the CSV file are not being correctly interpreted as numbers in the resulting Excel file. Instead, they appear in an undesired scientific format. Here's a simplified version of my function:

    import pandas as pd
    import os
    from tkinter import filedialog, messagebox

    def xlsx_conversion():
    file_paths = filedialog.askopenfilenames(filetypes=[("Text and CSV files", "*.txt *.csv")])
    if not file_paths:
    return

    for file_path in file_paths:
    try:
    sep = '\t' if file_path.lower().endswith('.txt') else ','
    df = pd.read_csv(file_path, sep=sep)

    for col in df.columns:
    df[col] = pd.to_numeric(df[col], errors='ignore')

    excel_file_path = os.path.splitext(file_path)[0] + '.xlsx'
    with pd.ExcelWriter(excel_file_path, engine='openpyxl') as writer:
    df.to_excel(writer, index=False, float_format="%.3f")

    except Exception as e:
    messagebox.showerror("Error", f"Error converting file {file_path}: {e}")
    return

    messagebox.showinfo("Success", "All files have been converted successfully!")

    xlsx_conversion()



    Here is an example of my csv file :

    [​IMG]

    And this is what i have after using the function :

    [​IMG]

    These data are unusable for creating graphs, which is the ultimate goal.

    Continue reading...

Compartilhe esta Página