简体   繁体   English

将字符串转换为 Pandas df

[英]Transform string to Pandas df

I have the string like that:我有这样的字符串:

'key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47' '键=IAfpK,年龄=58,键=WNVdi,年龄=64,键=jp9zt,年龄=47'

How can I transform it to Pandas DataFrame?如何将其转换为 Pandas DataFrame?

key钥匙 age年龄
0 0
1 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.一种快速且有点手动的方法是首先创建一个附加每个字符串的 dict 值列表。 Then convert that list to a dataframe.然后将该列表转换为数据框。 ( https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html ): 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.但是,这仅对您提到的特定字符串有效,如果您需要处理更长的字符串/更多数据,那么 for 循环会更有效。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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