【问题标题】:Creating a list of dictionaries from a list of lists in Python从 Python 中的列表列表创建字典列表
【发布时间】:2019-09-01 08:52:42
【问题描述】:

我的问题是关于如何从列表列表中创建字典列表,并且与这个问题Dict Comprehension python from list of lists 和这个问题List of Lists to List of Dictionaries 有偏差

我有一个很长的熊猫数据框,其中包含经纬度

     LAT        LON
     40         5
     40         6
     41         5
     42         8
     42         9

我设法将其转换为带有 towers.values 的列表列表(towers 是数据框的名称),其中每个列表的格式为 [lat,lon]

我的目标是拥有

list_dict = [{'lat': 40, 'lon': 5}, 
             {'lat': 40, 'lon': 6}, 
             {'lat': 41, 'lon': 5},
             {'lat': 41, 'lon': 5},
             {'lat': 42, 'lon': 8},
             {'lat': 42, 'lon': 9}]

我该怎么做?

【问题讨论】:

  • 别想了,试试towers.to_dict(orient='records')

标签: python python-3.x pandas list dictionary


【解决方案1】:
list_dict = [{'lat': df.loc[i, 'Lat'], 'lon' : df.loc[i, 'Lon']} for i in range(df.shape[0])]

正如@yatu 建议的那样,使用df.loc 比使用链式索引更有效。


data = zip(df['Lat'].tolist(), df['Lon'].tolist())
[{'lat': a, 'lon': b} for a, b in data]

【讨论】:

【解决方案2】:

遍历每一行数据帧可以给出解决方案。

res_list_of_dict = [{'lat':i[1][0], 'long':i[1][1]} for i in df.iterrows()]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 2020-03-07
    • 2018-03-21
    • 2020-11-17
    • 2018-04-27
    相关资源
    最近更新 更多