[Python] Converting pandas DataFrame to JSON array gives "only size-1 arrays can be converted...

Discussão em 'Python' iniciado por Stack, Setembro 9, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to read a CSV file and convert its contents to a JSON array, but I'm getting the error: "only size-1 arrays can be converted to Python scalars"

    The csv file contents are

    4.4.4.4
    5.5.5.5


    My code is below

    import numpy as np
    import pandas as pd
    df1 = pd.read_csv('/Users/Documents/datasetfiles/test123.csv', header=None)

    df1.head(5)
    0
    0 4.4.4.4
    1 5.5.5.5


    df_to_array = np.array(df1)
    app_json = json.dumps(df_to_array,default=int)


    Error i am getting

    TypeError: only size-1 arrays can be converted to Python scalars


    I need output as

    ["4.4.4.4", "5.5.5.5", "3.3.3.3"]


    What I've tried:

    Using np.array(df1) to convert the DataFrame to a numpy array

    Using json.dumps() with default=int parameter


    Question: Why am I getting this error, and what's the correct way to convert my DataFrame to a JSON array of strings?

    Continue reading...

Compartilhe esta Página