【问题标题】:how to turn Csv data to dictionary如何将 Csv 数据转换为字典
【发布时间】:2021-12-28 15:21:06
【问题描述】:

我使用 pandas 读取 csv 文件并能够从中创建字典,但需要将字典创建为特定格式。

flightinfo = pd.read_csv('flightdata.csv',quotechar='"',names=['starting_airport', 'destination_airport', 'airline', 'time', 'start_state','end_state'], header=None)

flightinfodict = flightinfo.to_dict(orient='records')

这给出了输出

[{'starting_airport': 'Hilo International Airport', 'destination_airport': 'Boise Airport ', 'airline': 'delta', 'average_time_taken': 300, 'start_state': 'HAWAII', 'end_state': 'IDAHO'}

但我需要的输出是

{'Hilo International Airport' : {'destination_airport': 'Boise Airport ', 'airline': 'delta', 'average_time_taken': 300}

如何修改代码以产生此输出

谢谢

【问题讨论】:

标签: python pandas csv dictionary


【解决方案1】:

starting_airport设置为索引并使用to_dict(orient='index')

flightinfodict.set_index('starting_airport').to_dict(orient='index')

输出:

{'Hilo International Airport': {'destination_airport': 'Boise Airport ',
  'airline': 'delta',
  'average_time_taken': 300,
  'start_state': 'HAWAII',
  'end_state': 'IDAHO'}}

或者:

df.set_index('starting_airport')[['destination_airport','airline','average_time_taken']].to_dict(orient='index')

因为您表明您只需要字典中的这三列。

【讨论】:

  • 感谢您的帮助,但我有 100 行数据并且 orient = 'index' 不适用于它返回的此方法,raise ValueError("DataFrame index must be unique for orient='index '.") ValueError: DataFrame 索引对于 orient='index' 必须是唯一的。
  • 这意味着您在starting_airport 列中有多个相似的值。因此,您想要的输出是不可能的(您不能拥有具有相似键的 dict)。我不确定你想要什么输出,但你可以试试这个:df.groupby('starting_airport')[['destination_airport','airline','average_time_taken']].apply(lambda x: x.to_dict('r')).to_dict()
【解决方案2】:

可能有一种更复杂的方法,但是这种面向记录的字典的处理应该可以完成这项工作:

def get_dict_without(d, key_to_remove):
  d.pop(key_to_remove)
  return d


new_flightinfodict = [{rec["starting_airport"]: get_dict_without(rec, "starting_airport")} for rec in flightinfodict]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 2018-12-09
    • 2021-07-31
    相关资源
    最近更新 更多