Skip to main content
 首页 » 编程设计

python之将列转换为字典并访问

2024年12月31日11qq78292959

我有以下数据框:

print(df.source) 
 
                    source 
0     "{'id': None, 'name': 'Cnet.com'}", 
1     "{'id': None, 'name': 'Cnet.com'}", 
2     "{'id': None, 'name': 'Cnet.com'}", 
 
... 

我想访问“名称”中包含的信息,最终创建:

print(df_final.source) 
 
                    source 
0                  Cnet.com 
1                  Cnet.com 
2                  Cnet.com 
 
... 

我试过:

dictio = df["source"].to_dict() 
 
for i in range(0, len(df)): 
 
     dictio[i]["name"] 

但它会引发错误:“TypeError:字符串索引必须是整数”。

如何创建 df_final?

请您参考如下方法:

通过ast将值转换为字典,然后通过get获取值:

import ast 
 
df['source'] = df['source'].apply(lambda x: ast.literal_eval(x).get("name", 'missing value')) 

或者如有必要,稍后使用字典列:

import ast 
 
df['source'] = df['source'].apply(ast.literal_eval) 
df['source'] = df['source'].apply(lambda x: x.get("name", 'missing value'))