pythonNinja
pythonNinja

Reputation: 499

Pandas csv dataframe to json array

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

Upvotes: 0

Views: 154

Answers (3)

BeRT2me
BeRT2me

Reputation: 13242

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~

Upvotes: 1

halfdanr
halfdanr

Reputation: 393

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

Upvotes: 1

pythonNinja
pythonNinja

Reputation: 499

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

Upvotes: 0

Related Questions