如何分割 pandas 系列的元素并将其放入JSON格式? [英] How to split elements of a pandas series and put them into JSON format?
问题描述
我有一个熊猫系列对象S,有些元素是名称-值"对,例如 12岁 b-23 c-42 d-25 ...
I have a pandas series object S, some elements are name-value pairs, like a-12 b-23 c-42 d-25 ...
有些只是 一种 b C d ....
some are just a b c d ....
等等,我需要做的是将其转换为Json格式,例如:
so on, what I need to do is to get this into Json format like:
{Name:a,Value:12}
{Name:b,Value:23}
{Name:c,Value:42}
{Name:d,Value:25}
...
如果仅a,b,c,d不成对,则值是NaN.
If only a, b, c, d, not pairs, Values is NaN.
我使用str.split(-")函数来分隔成对的结点,对于非结对,这会为值部分产生NaN.
I used str.split("-") function to separate the pairs, for non pairs this would produce NaN for the value part.
我想知道我是否可以像这样把它们放在一起
I wonder if I can put them together like
result=[{"Name": S.str.split("-").str.get(0),"Value": S.str.split("-").str.get(1)}]
?
推荐答案
是的,我认为您已经很接近了,您可以将其写为列表理解,例如
Yeah I think you're pretty close, you could would write it as a list comprehension like
result = [{"Name": n, "Value": v} for n, v in zip(S.str.split("-").str.get(0),
S.str.split("-").str.get(1))]
尽管使用正则表达式解析字符串可能会更好一些:
Although it might be a little nicer to use a regex to parse the string:
result = [{"Name": n, "Value": v} for n, v in S.str.extract("(\w)-?(\d+)?").values]
这篇关于如何分割 pandas 系列的元素并将其放入JSON格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!