How to split elements of a pandas series and put them into JSON format?

后端 未结 1 523
时光取名叫无心
时光取名叫无心 2021-01-28 04:16

I have a pandas series object S, some elements are name-value pairs, like a-12 b-23 c-42 d-25 ...

some are just a b c d

1条回答
  •  迷失自我
    2021-01-28 05:04

    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]
    

    0 讨论(0)
提交回复
热议问题