我有一个这样的DataFrame
Question Response
"How are you?" ["high","moderate"]
"how is it?" ["cool","low"]
我希望输出df像
Question Response
"How are you?" [{"weight":"1","Response":"high"},{"Weight":"2","Response":"moderate"}]
"how is it?" [{"weight":"1","Response":"cool"},{"Weight":"2","Response":"low"}]
答案 0 :(得分:0)
使用map
(
通常非常快):
df['Response'] = list(map(lambda val: list(map(lambda d:{'Weight' : d[0],
'Response' : d[1]},
enumerate(val, 1))),
df['Response']))
或comprehension list
df['Response'] = [[{'Weight' : weight, 'Response' : response}
for weight, response in enumerate(val, 1)]
for val in df['Response']]
输出
print(df)
Question \
0 "How are you?"
1 "how is it?"
Response
0 [{'Weight': 1, 'Response': 'high'}, {'Weight': 2, 'Response': 'moderate'}]
1 [{'Weight': 1, 'Response': 'cool'}, {'Weight': 2, 'Response': 'low'}]
答案 1 :(得分:0)
我们可以编写一个自定义函数来创建您的字典:
def convert_list(x):
lst = [{'weight': i+1, 'Reponse': val} for i, val in enumerate(x)]
return lst
df['Reponse'] = df['Response'].apply(lambda x: convert_list(x))
Question \
0 "How are you?"
1 "how is it?"
Response
0 [{'weight': 1, 'Reponse': 'high'}, {'weight': 2, 'Reponse': 'moderate'}]
1 [{'weight': 1, 'Reponse': 'cool'}, {'weight': 2, 'Reponse': 'low'}]