python - 使用 Pandas 从字典列中提取值

标签 python python-3.x pandas dictionary dataframe

我正在尝试从以下字典中提取名称:

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/

相关文章:

python - 使用给定的时间增量对时间序列进行重采样

python - 删除数据框中每天的最后 2 行

python - 在 Python 中捕获 KeyError

python - (Visual Studio代码上的Python)SyntaxError : invalid syntax

python - 如何按索引顺序拆分 pandas.DataFrame?

django - Geodjango 创建一个新的 SRID

python - 替换文件内容中的字符串

python - 没有绘图功能的直方图

python - MySQL: django.db.utils.OperationalError: (1698, "Access denied for user ' root' @'localhost' ") with correct username and pw

python - 如何在条件中用另一列值替换一列值