[Python] how to convert a double field to a string field remove decimal and zero

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    in a r script why when converting a double field to a character field, it adds a dot and a decimal to a duckdb table, how can i fix this?

    import duckdb

    # Connect to DuckDB database
    con = duckdb.connect(database=':memory:')

    # Create a sample table for demonstration
    con.execute("""
    CREATE TABLE my_table (
    id INTEGER,
    double_column DOUBLE
    )
    """)
    con.execute("""
    INSERT INTO my_table VALUES
    (1, 10.5),
    (2, 20.7),
    (3, 30.9)
    """)

    # Add a new column to store the converted result
    con.execute("""
    ALTER TABLE my_table
    ADD COLUMN string_column VARCHAR
    """)

    # Convert DOUBLE to VARCHAR and remove decimals
    con.execute("""
    UPDATE my_table
    SET string_column = TRIM(TRAILING '.' FROM CAST(double_column AS VARCHAR))
    """)

    # Display the updated table
    updated_table = con.execute("SELECT * FROM my_table").fetchdf()
    print(updated_table)

    # Disconnect from the database
    con.close()

    Continue reading...

Compartilhe esta Página