-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?

5
  • import pandas as pd string = "id=IAfpK, val=58, id=WNVdi, val=64, id=jp9zt, val=47" df = pd.DataFrame({'String' : [string]}) df Commented Aug 21, 2020 at 23:32
  • @DavidErickson i want a dataframe with two columns and of length 3 as there are 3 key, val pairs Commented Aug 21, 2020 at 23:35
  • makes sense. These details should be in your question if you can modify it and make it clear exactly what you want. Commented Aug 21, 2020 at 23:37
  • @DavidErickson If there is no duplicate why to vote to close it ! Commented Aug 21, 2020 at 23:38
  • I retracted my vote, since it is not as simple as the code I copy and pasted above after you have explained it. Commented Aug 21, 2020 at 23:39

1 Answer 1

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)]
    }
)
Sign up to request clarification or add additional context in comments.

2 Comments

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
Sorry, the comments can't format it properly. Just add a newline on each ....

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.