Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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数据帧到嵌套字典_Python_Python 3.x - Fatal编程技术网

从Python数据帧到嵌套字典

从Python数据帧到嵌套字典,python,python-3.x,Python,Python 3.x,我想使用一个api,需要先将我的数据帧放在字典格式中。 数据帧df如下所示: OrigC OrigZ OrigN Weigh DestC DestZ DestN 0 PL 97 TP 59 DE 63 SN 第一行的示例输出: 请注意,字典中有不需要任何更改的静态信息 如何在Python中实现这一点?您可以使用ItErrors dic = {} dic['section'] = [] for ix, row i

我想使用一个api,需要先将我的数据帧放在字典格式中。 数据帧df如下所示:

    OrigC  OrigZ  OrigN Weigh  DestC   DestZ    DestN
0      PL     97    TP    59     DE      63       SN
第一行的示例输出:

请注意,字典中有不需要任何更改的静态信息

如何在Python中实现这一点?

您可以使用ItErrors

dic = {}
dic['section'] = []
for ix, row in df.iterrows():
    
    in_dict = {
        'location': {
            'zip_code': {
                'OrigC': row['OrigC'],
                'OrigZ': row['OrigZ'],
                },
            'location': {'id': ix+1}, # I am guessing here.
            'OrigN': 'TP',  
        },
        'CarriageParameter': {
            'road': {
                'truckLoad': 'Auto'}
            },
        'load': {
            'Weigh': str(row['Weigh']),
        } 
        }
    
    
    dic['section'].append(in_dict)
请注意,这不是完整的条目,但我认为它足够清楚地说明这个想法。

您可以使用ItErrors

dic = {}
dic['section'] = []
for ix, row in df.iterrows():
    
    in_dict = {
        'location': {
            'zip_code': {
                'OrigC': row['OrigC'],
                'OrigZ': row['OrigZ'],
                },
            'location': {'id': ix+1}, # I am guessing here.
            'OrigN': 'TP',  
        },
        'CarriageParameter': {
            'road': {
                'truckLoad': 'Auto'}
            },
        'load': {
            'Weigh': str(row['Weigh']),
        } 
        }
    
    
    dic['section'].append(in_dict)

请注意,这不是完整的条目,但我认为它足够清楚地说明了这个想法。

谢谢@warped,我尝试了代码,但输出上没有打印任何内容,没有显示错误。您想打印什么?预期输出printdic中描述的字典结构?感谢lotThanks@warped,我尝试了代码,执行了,但是输出上没有打印任何内容,没有显示错误。您想打印什么?预期输出printdic中描述的字典结构?非常感谢