如何在列表到行中设置转换集

原始df

import pandas as pd

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

期望的输出

import pandas as pd

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

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

我尝试了什么,但是这看起来很“怪异”,通过尝试逐一删除标点符号,然后仅转换为行

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

有没有更好的方法将列表转换为所需的行和列? 谢谢

评论
  • 幸福棒棒糖
    幸福棒棒糖 回复

    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       sour         5
    1  lemon  very sour         0