Calamari Calamari - 1 year ago 155
Python Question

Python reshaping a list of strings based on delimiter

I have pipe delimited data being returned from a Rest API call:

data = ['Bob|37', 'Eric|40']

I extracted the header info from the first "line" and split it into a list:

column_list = ['Name','Age']

I am trying to read this into a pandas dataframe:


Unsurprisingly it's complaining about the data being in the wrong shape

"ValueError: Shape of passed values is (1, 2), indices imply (2, 2)"

What's the best way to split the strings within the data list to be able to load it in the dataframe?

Answer Source

Try this:

data = ['Bob|37', 'Eric|40']

df = pd.Series(data).str.split('|', expand=True)
df.columns = ['Name', 'Age']
print df

   Name Age
0   Bob  37
1  Eric  40
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download