我正在尝试从以下字典中提取名称:
df = df[[x.get('Name') for x in df['Contact']]]
下面是我的 Dataframe 的样子:
data = [{'emp_id': 101,
'name': {'Name': 'Kevin',
'attributes': {'type': 'Contact',
'url': '/services/data/v38.0/sobjects/Contact/00985300000bt4HEG4'}}},
{'emp_id': 102,
'name': {'Name': 'Scott',
'attributes': {'type': 'Contact',
'url': '/services/data/v38.0/sobjects/Contact/00985300000yr5UTR9'}}}]
df = pd.DataFrame(data)
df
emp_id name
0 101 {'Name': 'Kevin', 'attributes': {'type': 'Cont...
1 102 {'Name': 'Scott', 'attributes': {'type': 'Cont...
我得到一个错误:
AttributeError: 'NoneType' object has no attribute 'get'
最佳答案
如果没有 NaN,则使用 json_normalize
。
pd.io.json.json_normalize(df.name.tolist())['Name']
0 Kevin
1 Scott
Name: Name, dtype: object
如果有 NaN,您需要先删除它们。但是,保留索引很容易。
df
emp_id name
0 101.0 {'Name': 'Kevin', 'attributes': {'type': 'Cont...
1 102.0 NaN
2 103.0 {'Name': 'Scott', 'attributes': {'type': 'Cont...
idx = df.index[df.name.notna()]
names = pd.io.json.json_normalize(df.name.dropna().tolist())['Name']
names.index = idx
names
0 Kevin
2 Scott
Name: Name, dtype: object
关于python - 使用 Pandas 从字典列中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53826771/