2

fellow developers in the StackOverflow. I have string data in 'key=apple; age=10; key=boy; age=3' How can we convert it into the pandas' data frame such that key and age will be the header and all the values in the column?

key   age
apple 10
boy   3

2 Answers 2

4

Try this:

import pandas as pd

data = 'key=apple; age=10; key=boy; age=3'
words = data.split(";")
key = []
age = []

for word in words:
    if "key" in word:
        key.append(word.split("=")[1])
    else:
        age.append(word.split("=")[1])

df = pd.DataFrame(key, columns=["key"])
df["age"] = age

print(df)
Sign up to request clarification or add additional context in comments.

Comments

1

You can try this:

import pandas as pd
str_stream = 'key=apple; age=10; key=boy; age=3'
lst_kv = str_stream.split(';')   
# lst_kv => ['key=apple', ' age=10', ' key=boy', ' age=3']

res= [{s.split('=')[0].strip(): s.split('=')[1] for s in lst_kv[i:i+2]} 
      for i in range(len(lst_kv)//2)
     ]
df = pd.DataFrame(res)
df

Output:

    key     age
0   apple   10
1   boy     10

More explanation for one line res :

res = []
for i in range(len(lst_kv)//2):
    dct_tmp = {}
    for s in lst_kv[i:i+2]:
        kv = s.split('=')
        dct_tmp[kv[0].strip()] = kv[1]
    res.append(dct_tmp)
res

Output:

[{'key': 'apple', 'age': '10'}, {'age': '10', 'key': 'boy'}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.