Home > Mobile >  Pandas csv dataframe to json array
Pandas csv dataframe to json array

Time:09-12

I am reading a csv file and trying to convert the data into json array.But I am facing issues as "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)

I need output as

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

CodePudding user response:

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"]

CodePudding user response:

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]))
  • Related