-1

I have this string

"id=IAfpK, val=58, id=WNVdi, val=64, id=jp9zt, val=47"

. I want to create a pandas data frame out of it. Any ideas how to do so?

jasraj bedi
  • 113
  • 5

1 Answers1

1
import pandas as pd

data = "id=IAfpK, val=58, id=WNVdi, val=64, id=jp9zt, val=47"

data = [*map(lambda x: x.split('='), data.split(', '))]
ids = [*filter(lambda x: x[0] == 'id', data)]
vals = [*filter(lambda x: x[0] == 'val', data)]

df = pd.DataFrame.from_dict(
    data={
        'id': [*map(lambda x: x[1], ids)],
        'val': [*map(lambda x: x[1], vals)]
    }
)
Dimitri Sifoua
  • 490
  • 5
  • 17
  • Useful only for a very short data and is just unnecessarily complex. Not everything has to be a `map()`, `lambda` or `filter()`. Use it where necessary/useful and always use `timeit` when using too many of them. In my experience it's harder to read and worse code overall (but has its uses). Instead: ```>>> def better(data): ... from collections import defaultdict as ddict ... out = ddict(list) ... data = [it.split("=") for it in [item.strip() for item in data.split(",")]] ... for key, val in data: ... out[key].append(val) ... return out``` – Peter Badida Aug 22 '20 at 00:06
  • Sorry, the comments can't format it properly. Just add a newline on each `...`. – Peter Badida Aug 22 '20 at 00:08