Calamari Calamari - 3 months ago 11x
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?


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