Python 将列转换为字典并访问
我有以下数据帧:Python 将列转换为字典并访问,python,pandas,dictionary,Python,Pandas,Dictionary,我有以下数据帧: 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)
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'))
问题是源列中的数据是字符串格式的。 我们可以尝试使用
json
包将字符串转换为字典格式,然后从中访问name字段
我认为这个片段应该有用
import json
for index, row in df.iterrows():
sourceDict = json.loads(row['source'])
name = sourceDict['name']
您必须执行
df['source']=df['source'].apply(lambda x:x['name'])
这假设您在所有行中都有一个dict,并且所有dict中都存在键'name'
:TypeError:'int'对象不可订阅“,如果在传递该列之前将其转换为字典;否则它将引发:TypeError:字符串索引必须是整数“如果您使用.apply(lambda x:x.get(“name”,default))
您可以提供默认值default
,如果dict中不存在“name”,则返回该值。