【问题标题】:Looping dictionaries from Pandas从 Pandas 循环字典
【发布时间】:2018-08-18 00:39:07
【问题描述】:

我正在尝试从 Pandas 表创建 ts 字典,但无法实现。

我的桌子:

         Bool       name       station_id           Coords
0        True       item1          1        19.28152437,47.78960029
1        True       item2          2        20.15190158,46.25528206

我想要的输出:

a= {
    'item1':[ 19.28152437,47.78960029],
    'item2':[20.15190158,46.25528206],
}

我正在使用 iterrows 来做到这一点:

for i, c in allomasok.iterrows():
     //here is the problem, I can't add name of the dict item 

【问题讨论】:

  • 字典a 列表中的值在上面的示例中不存在。 b 是字典列表,而不是字典本身。你能澄清你的问题,也许可以把它背景化吗?如果你想使用不可变的可迭代对象,你可以尝试使用元组
  • 我更正了,抱歉我的错字。

标签: python pandas dictionary for-loop itertools


【解决方案1】:

您可以将pd.DataFrame.set_indexpd.DataFrame.to_dict 结合使用:

df = pd.DataFrame({'name': ['item1', 'item2'],
                   'Coord': ['19.28152437,47.78960029', '20.15190158,46.25528206']})

df['Coord'] = df['Coord'].apply(lambda x: list(map(float, x.split(','))))
d = df.set_index('name')['Coord'].to_dict()

# {'item1': [19.28152437, 47.78960029], 'item2': [20.15190158, 46.25528206]}

【讨论】:

  • 不幸的是我从我的DataFrame: {'item1': '16.09016385, 46.74074716 ', 'item2': '17.00062128, 46.46736962 '} 得到这个。上表是左连接表,所以表已经是DataFrame了。
  • 我编辑了我的问题。我输入了错误的坐标,但问题是:如何从我的 Pandas DataFrame 表的两列(名称、坐标)创建所需的输出。
猜你喜欢
  • 2018-12-30
  • 2020-08-03
  • 2021-12-14
  • 1970-01-01
  • 2020-02-10
  • 2021-02-27
  • 2014-09-29
  • 2022-01-05
  • 2017-05-09
相关资源
最近更新 更多