Jonathan
Jonathan

Reputation: 125

How to make a convert set in list to row

original df

list1 = ['apple','lemon']
list2 = [[('taste','sweet'),('sweetness','5')],[('taste','sour'),('sweetness','0')]]
df = pd.DataFrame(list(zip(list1,list2)), columns=['fruit', 'description'])
df.head()

desired output

list3 = ['apple','lemon']
list4 = ['sweet','sour']
list5 = ['5','0']

df2 = pd.DataFrame(list(zip(list3,list4,list5)), columns=['fruit', 'taste', 'sweetness'])
df2.head()

what had i tried, but this seem 'weird', by trying to remove punctuation one by one, then only convert to row

df['description'] = df['description'].astype(str)
df['description'] = df['description'].str[1:-1]
df['description'] = df['description'].str.replace("(","")
df.head()

is there a better way to convert the list to desired row and column? Thanks

Upvotes: 1

Views: 123

Answers (1)

jezrael
jezrael

Reputation: 862511

Create dictionaries from tuples and pass to DataFrame constructor with DataFrame.pop for extract column, last append to original by DataFrame.join:

L = [dict(y) for y in df.pop('description')]
df = df.join(pd.DataFrame(L, index=df.index))
print (df)
   fruit      taste sweetness
0  apple      sweet         5
1  lemon       sour         0

Upvotes: 1

Related Questions