Playing With BI
Playing With BI

Reputation: 421

Convert Pandas df Column to JSON String

Having the following pandas dataframe:

from pandas import *
df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})

It looks like:

    bar foo
0    1   a
1    2   b
2    3   c

How could I get for every row the following string pattern:`

{"telemetry":{"a":1}}

Upvotes: 2

Views: 560

Answers (1)

jezrael
jezrael

Reputation: 863801

Use list comprehension with dictionary:

a = [{"telemetry":{a:b}} for a, b in df[['foo','bar']].to_numpy()]
print (a)
[{'telemetry': {'a': 1}}, {'telemetry': {'b': 2}}, {'telemetry': {'c': 3}}]

If need jsons:

import json

b = [json.dumps({"telemetry":{a:b}}) for a, b in df[['foo','bar']].to_numpy()]
print (b)
['{"telemetry": {"a": 1}}', '{"telemetry": {"b": 2}}', '{"telemetry": {"c": 3}}']

c = json.dumps([{"telemetry":{a:b}} for a, b in df[['foo','bar']].to_numpy()])
print (c)
[{"telemetry": {"a": 1}}, {"telemetry": {"b": 2}}, {"telemetry": {"c": 3}}]

Upvotes: 3

Related Questions