微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

具有相同键的字典列表,需要用返回键列名

如何解决具有相同键的字典列表,需要用返回键列名

我对 Pandas 和数据预处理很陌生。我有一个任务,我得到了一个包含列的数据集,其中每一行都包含具有相同键的字典列表,请检查下图

enter image description here

我想要实现的是为新的 Plates 列下的每一行获取一个 listvalues 板的 list。 必须看起来像这样

enter image description here

这是需要清理的样本数据。 考生 "[{'plate': 'ap26tl0624'},{'plate': 'ap26tl0624'}]" [{'板':'1111'}] “[{'plate':'ap1gth6815'},{'plate':'ap16th6815'},{'plate':'ap16thg815'},{'plate':'ap16thg815'}]” [{'板':'2gce6935'}] "[{'plate': 'ap16tbc815'},{'plate': 'ap1676318'}]" “[{'plate':'ap26ce6935'},{'plate':'ap26ce6935'},{'plate':'ap26ce6933'},{'plate':'ap26ce6935'}]” "[{'plate': 'ap26ch1629'},{'plate': 'ap26ch1629'},{'plate': 'ap26ch1623'},{'plate': 'ap26ch1629'}]" “[{'plate': 'ap20185'},{'plate': 'ai20186'}]” [{'板':'br06bp5210'}] “[{'plate':'ap39dg9428'},{'plate':'ap39dg9428'},{'plate':'ap39dg9428'},{'plate':'br06bd4347'}]” [{'板':'rj26ca6690'}]

有人可以看看这个吗。

提前致谢

解决方法

编辑回答是为了满足请求的数据格式。

请尝试以下操作:

# generate test dataframe
df_test = pd.DataFrame([[0,[{'plate':'2323'},{'plate':'13'}]],[1,[{'plate':'2323'}]]],columns=['ids','candidate'])

def get_plates(row):
    # function that returns list of plates from your data structure
    # EDITED
    if type(row['candidate']) == str:
        return [dict_value['plate'] for dict_value in eval(row['candidate'])]
    else:
        return [dict_value['plate'] for dict_value in row['candidate']]

# applying function get_plates to each row and save to column df['Plates']
df_test ['Plates'] = df_test .apply(get_plates,axis = 1)

df_test 

enter image description here

以下是请求数据格式的函数输出示例

test_data = [
    "[{'plate': 'ap26tl0624'},{'plate': 'ap26tl0624'}]",[{'plate': '1111'}],"[{'plate': 'ap1gth6815'},{'plate': 'ap16th6815'},{'plate': 'ap16thg815'},{'plate': 'ap16thg815'}]",[{'plate': '2gce6935'}],"[{'plate': 'ap16tbc815'},{'plate': 'ap1676318'}]","[{'plate': 'ap26ce6935'},{'plate': 'ap26ce6935'},{'plate': 'ap26ce6933'},{'plate': 'ap26ce6935'}]","[{'plate': 'ap26ch1629'},{'plate': 'ap26ch1629'},{'plate': 'ap26ch1623'},{'plate': 'ap26ch1629'}]","[{'plate': 'ap20185'},{'plate': 'ai20186'}]",[{'plate': 'br06bp5210'}],"[{'plate': 'ap39dg9428'},{'plate': 'ap39dg9428'},{'plate': 'br06bd4347'}]",[{'plate': 'rj26ca6690'}]
]



test_data_df = pd.DataFrame(test_data,columns=['candidate'])
test_data_df['Plates'] = test_data_df.apply(get_plates,axis = 1)
test_data_df

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。