使用Pandas Dataframe创建字典

2024-10-01 19:30:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个称为“df”的数据帧,如下所示

enter image description here

我的目标是编一本字典。对于dictionary,键是poid,值是lng和lat

示例字典输出

{0: (30.2359091167, -97.7951395833),
 1: (30.2691029532, -97.7493953705),
 2: (30.2557309927, -97.7633857727),
 3: (30.2634181234, -97.7575966669),
 4: (30.2742918584, -97.7405226231),
 5: (30.261599404, -97.7585805953),
...

我的解决方案

dictionary = df.groupby('poiid')['lng'].agg(set).to_dict()

我的解决方案有效,但我无法将“lat”列添加到字典中。

我愿意看到其他解决办法


Tags: to数据示例目标dfdictionary字典解决方案
2条回答

您应该使用df = df.set_index("poiid")将POID设置为索引,然后使用df.to_dict("index")

首先将索引设置为poiid,这样当您想要创建字典时,键将是poiid。然后获取所需的列并使它们tuple。在最后一步中,您将使用它创建一个字典

df = df.set_index('poiid')[['lng', 'lat']].apply(tuple, axis=1).to_dict()

相关问题 更多 >

    热门问题