从列创建数据框

问题描述 投票:0回答:1

我有一个数据框

df
,其中有一列
prediction
prediction
列的值是字典列表。列
prediction
的典型行如下所示:

[{'answer': 'My name is Andrew.',
  'text': 'What is your name ?',
  'id': 1},
 {'answer': 'I live at California.',
  'text': 'Where do you live ?',
  'id': 2},
 {'answer': 'I want to become a doctor.',
  'text': 'What do you want to do ?',
  'id': 3}]

我想将列

prediction
转换为单独的数据框,其中键
text
的值作为列名称,
answer
作为行。示例:

What is your name ?      Where do you live?        What do you want to do?   
My name is Andrew        I live at California      I want to become a doctor.
My name is Julie         I live at NY              I want to be a cook.

请建议如何做到这一点。

pandas dataframe dictionary
1个回答
0
投票

IIUC用途:

L = [{'answer': 'My name is Andrew.',
  'text': 'What is your name ?',
  'id': 1},
 {'answer': 'I live at California.',
  'text': 'Where do you live ?',
  'id': 2},
 {'answer': 'I want to become a doctor.',
  'text': 'What do you want to do ?',
  'id': 3}]

df = pd.DataFrame({x['text']:[x['answer']] for x in L})
print (df)
  What is your name ?    Where do you live ?    What do you want to do ?
0  My name is Andrew.  I live at California.  I want to become a doctor.
© www.soinside.com 2019 - 2024. All rights reserved.