简体   繁体   中英

Transform string to Pandas df

I have the string like that:

'key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47'

How can I transform it to Pandas DataFrame?

key age
0
1

Thank you

Use:

In [919]: s = 'key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47'
In [922]: d = {}

In [927]: for i in s.split(', '):
     ...:     ele, val = i.split('=')
     ...:     if ele in d:
     ...:         d[ele].append(val)
     ...:     else:
     ...:         d[ele] = [val]
     ...: 
In [930]: df = pd.DataFrame(d)

In [931]: df
Out[931]: 
     key age
0  IAfpK  58
1  WNVdi  64
2  jp9zt  47

A quick and somewhat manual way to do it would be to first create a list of dict values appending each string. Then convert that list to a dataframe. ( https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html ):

import pandas as pd

keylist = []
keylist.append({"key": 'IAfpK', "age": '58'})
keylist.append({"key": 'WNVdi', "age": '64'})
keylist.append({"key": 'jp9zt', "age": '47'})

#convert the list of dictionaries into a df
key_df = pd.DataFrame(keylist, columns = ['key', 'age'])

However, this is only efficient for that specific string you mentioned, if you need to work on a longer string/more data then a for loop would be more efficient.

Although I think this answers your question, there are probably more optimal ways to go about it :)

Try:

s = "key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"

x = (
    pd.Series(s)
    .str.extractall(r"key=(?P<key>.*?),\s*age=(?P<age>.*?)(?=,|\Z)")
    .reset_index(drop=True)
)
print(x)

Prints:

     key age
0  IAfpK  58
1  WNVdi  64
2  jp9zt  47

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM