Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python ';非类型';对象在OrderedDict-dataframe中不可下标_Python_Pandas_Dictionary_Dataframe_Ordereddictionary - Fatal编程技术网

Python ';非类型';对象在OrderedDict-dataframe中不可下标

Python ';非类型';对象在OrderedDict-dataframe中不可下标,python,pandas,dictionary,dataframe,ordereddictionary,Python,Pandas,Dictionary,Dataframe,Ordereddictionary,我正试图将信息从有序字典中提取到一个数据框中。有序的dict是从查询到数据库的。为了将信息上传回数据库并对其进行操作,我需要数据帧格式 我一直在使用以下方法将有序dict转换为一个pd.DataFrame: 有序Dict示例: x = [OrderedDict([('attributes', OrderedDict([('type', 'User'), ('url',

我正试图将信息从有序字典中提取到一个数据框中。有序的dict是从查询到数据库的。为了将信息上传回数据库并对其进行操作,我需要数据帧格式

我一直在使用以下方法将有序dict转换为一个
pd.DataFrame

有序Dict示例:

x = [OrderedDict([('attributes',
               OrderedDict([('type', 'User'),
                            ('url',
                             '/services/data/v38.0/sobjects/User/0051300000C2dczAAB')])),
              ('Id', '0051300000C2dczAAB'),
              ('UserRole',
               OrderedDict([('attributes',
                             OrderedDict([('type', 'UserRole'),
                                          ('url',
                                           '/services/data/v38.0/sobjects/UserRole/00E1B000002DT6bUAG')])),
                            ('Name', 'Platform NA')]))]),
 OrderedDict([('attributes',
               OrderedDict([('type', 'User'),
                            ('url',
                             '/services/data/v34.0/sobjects/User/005a0000007oQYSST2')])),
              ('Id', '005a0000007oQYSST2'),
              ('UserRole', None)])]



df = pd.DataFrame(
           dict(Id = rec['Id'],
                UserRole = rec['UserRole']['Name']) for rec in x)
这一直很有效,除非我有一个记录,其中(在本例中)
UserRole
没有底层记录。我得到的错误是,
'NoneType'对象不可订阅
,因为我试图从
orderedict
中提取
['Name']
,即
x['UserRole']
。我曾尝试创建另一个生成器来解决这个问题,或者创建一个for循环,但没有成功。这个示例有两个特性,我的真实数据集是10多个特性,其中一些特性(并非所有特性)中没有记录


非常感谢您的帮助

您可以有一个helper函数

def helper(x, attribute):
    return None if x is None else x[attribute]

df = pd.DataFrame(
           dict(Id = rec['Id'],
                UserRole = helper(rec['UserRole'], "Name")) for rec in x)

杰出的非常感谢@Tai@MattW. 没问题:P