1

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?

5
  • can you share sample datain test123.csv Commented Sep 12, 2022 at 3:26
  • Also in your code you are importing numpy as np and pd as well... Commented Sep 12, 2022 at 3:26
  • 1
    why not list(df1[0]) Commented Sep 12, 2022 at 3:29
  • @bn_ln list gives values in single quotes ,I need in double quotes as json array Commented Sep 12, 2022 at 3:32
  • 1
    ok thanks @bn_ln ,i added as like this and it worked import json df_to_array = list(df1[0]) app_json = json.dumps(df_to_array,default=int) print(app_json) ["4.4.4.4", "5.5.5.5"] Commented Sep 12, 2022 at 3:33

3 Answers 3

1

As other answers mentioned, just use list: json.dumps(list(df[0]))

FYI, the data shape is your problem:

enter image description here

if you absolutely must use numpy, then transpose the array first:

json.dumps(list(df_to_array.transpose()[0]))
Sign up to request clarification or add additional context in comments.

Comments

1

Given test.csv:

4.4.4.4
5.5.5.5

Doing:

import json

with open('test.csv') as f:
    data = f.read().splitlines()

print(data)
print(json.dumps(data))

Output:

['4.4.4.4', '5.5.5.5']
["4.4.4.4", "5.5.5.5"]

You're overcomplicating things using pandas is this is all you want to do~

Comments

0
import json
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 = list(df1[0]) 
app_json = json.dumps(df_to_array,default=int)

print(app_json)
["4.4.4.4", "5.5.5.5", "3.3.3.3"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.