I have a list of strings which looks like this:
["Name: Alice, Department: HR, Salary: 60000", "Name: Bob, Department: Engineering, Salary: 45000"]
I would like to convert this list into a DataFrame that looks like this:
Name | Department | Salary
--------------------------
Alice | HR | 60000
Bob | Engineering | 45000
What would be the easiest way to go about this? My gut says throw the data into a CSV and separate titles with regex "^.*:", but there must be a simpler way
With some string processing you can get a list of dicts and pass that to the DataFrame constructor:
lst = ["Name: Alice, Department: HR, Salary: 60000",
"Name: Bob, Department: Engineering, Salary: 45000"]
pd.DataFrame([dict([kv.split(': ') for kv in record.split(', ')]) for record in lst])
Out:
Department Name Salary
0 HR Alice 60000
1 Engineering Bob 45000
you can do it this way:
In [271]: s
Out[271]:
['Name: Alice, Department: HR, Salary: 60000',
'Name: Bob, Department: Engineering, Salary: 45000']
In [272]: pd.read_csv(io.StringIO(re.sub(r'\s*(Name|Department|Salary):\s*', r'', '~'.join(s))),
...: names=['Name','Department','Salary'],
...: header=None,
...: lineterminator=r'~'
...: )
...:
Out[272]:
Name Department Salary
0 Alice HR 60000
1 Bob Engineering 45000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With