简体   繁体   English

将 Pandas df 列转换为 JSON 字符串

[英]Convert Pandas df Column to JSON String

Having the following pandas dataframe:具有以下 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}}

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:如果需要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}}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM