具有以下熊猫数据框:
from pandas import *
df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})
看起来像:
bar foo
0 1 a
1 2 b
2 3 c
我如何为每一行获取以下字符串模式:
{"telemetry":{"a":1}}
将列表理解与字典一起使用:
a = [{"telemetry":{a:b}} for a, b in df[['foo','bar']].to_numpy()]
print (a)
[{'telemetry': {'a': 1}}, {'telemetry': {'b': 2}}, {'telemetry': {'c': 3}}]
如果需要json:
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}}]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句