熊猫通过列字典访问特定值

时间:2020-05-31 21:18:58

标签: python pandas dictionary

我有一个具有这种格式的字典的数据框(列名称为'due'):

{'date': '2020-05-21', 'is_recurring': False, 'lang': 'en', 'string': 'May 21', 'timezone': None}
None

我正尝试使用以下代码获取项目“日期”:

print(df.due.apply(lambda x: x['date']))

但是我遇到了以下错误:

TypeError: 'NoneType' object is not subscriptable

因此,我正尝试将None转换为NA,以避免发生此错误(最佳做法是)。为此,我正在使用此:

df['due'] = np.where(df['due'] is None, np.nan, df['due'])

但是,“无”行继续显示为“无”。我在做什么错了?

谢谢!

1 个答案:

答案 0 :(得分:3)

您的栏中可能有NaN:

df
                                                 due
0  {'date': '2020-05-21', 'is_recurring': False, ...
1                                                NaN

在这种情况下,pandas提供了str.get(或.str[..]的缩写)作为索引对象的“安全”方法:

df['due'].str['date']

0    2020-05-21
1           NaN
Name: due, dtype: object