[英]How to create a dictionary from a dataframe, being the index the only key?
我有一個名為la_crime_refined
的數據la_crime_refined
,如下所示:
DR_NO AREA NAME LOCATION LAT LON
0 10304468 Southwest 1100 W 39TH PL 34.0141 -118.2978
1 190101086 Central 700 S HILL ST 34.0459 -118.2545
2 201418201 Pacific 4700 LA VILLA MARINA 33.9813 -118.4350
3 191501505 N Hollywood 5400 CORTEEN PL 34.1685 -118.4019
4 191921269 Mission 14400 TITUS ST 34.2198 -118.4468
我想創建一個字典,其中包含具有唯一鍵的緯度和經度:索引。 我試過這個:
crime_cord = la_crime_refined[['LAT','LON']].to_dict(orient='index')
但是,它為字典中的每個條目返回鍵名“LAT”和“LON”。
{0:{'LAT':34.0141,'LON',-118.2978},1:{...}...}
有沒有辦法獲得如下所示的輸出:
{0:(34.0141,-118.2978),1:(...)...}
謝謝!
如果您不介意采取額外的步驟,您可以簡單地遍歷從to_dict
方法返回的字典:
res = {}
for k, v in la_crime_refined[['LAT','LON']].to_dict(orient='index').items():
res[k] = (v['LAT'], v['LON'])
或者,您可以遍歷數據幀的行(循環或字典理解),例如
res = {idx: (row['LAT'], row['LON']) for idx, row in la_crime_refined.iterrows()}
由於您已經在 {'LAT'=X, 'LON'=Y} 中有格式,最簡單的方法可能是簡單地使用它作為基礎來生成您想要的格式:
old_format = {0:{'LAT':34.0141,'LON':-118.2978}, 1:{'LAT':50.0141,'LON':-120.2978}, 2:{'LAT':60,'LON':-130}}
print(old_format)
new_format = {}
for key in old_format.keys():
new_format[key] = (old_format[key]['LAT'], old_format[key]['LON'])
print(new_format)
嘗試字典理解:
{k: tuple(v.values()) for k, v in crime_cord.items()}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.