5

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

1
  • This is pretty simple. So, before we give you the answer, what have you done to find the answer yourself? Hint: It is a comma delimited string array of k=>v pairs (delimited by :) Commented Nov 7, 2016 at 15:48

3 Answers 3

12

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

Comments

2

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

Comments

2

a little creative

s.str.extractall(r'(?P<key>[^,]+)\s*:(?P<value>[^,]+)') \
    .reset_index('match', drop=True) \
    .set_index('key', append=True).value.unstack()

enter image description here

setup

l = ["Name: Alice, Department: HR, Salary: 60000",
     "Name: Bob, Department: Engineering, Salary: 45000"]
s = pd.Series(l)

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.