Skip to content
Advertisement

Convert each row of pandas DataFrame to a separate Json string

I use this code in order to convert each row of pandas DataFrame df into Json string. The problem is that it’s printing None, however df.head() prints out the data.

import pandas as pd
import json

df = pd.read_csv('mydataset.csv')

for i in df.index:
    print df.loc[i].to_json("row{}.json".format(i))
    if i==10:
        break

How to get each row as a Json string variable and print it out? The Json string’s structure is plain, no arrays, just string, integer and float fields.

Advertisement

Answer

Use apply with parameter axis=1 for process by rows:

df.apply(lambda x: x.to_json("row{}.json".format(x.name)), axis=1)

If want only see output:

df.apply(lambda x: print(x.to_json()), axis=1)

EDIT:

Use custom function:

def f(x):
    a = x.to_json()
    print (a)


df.apply(f, axis=1)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement