【问题标题】:convert dataframe row to dict将数据框行转换为字典
【发布时间】:2018-11-07 14:29:58
【问题描述】:

我有如下示例数据的数据框。我正在尝试将数据帧中的一行转换为字典,如下面所需的输出。但是当我使用 to_dict 时,我会得到索引以及列值。有谁知道如何将行转换为所需输出的字典?非常感谢任何提示。

Sample data:

print(catStr_df[['Bottle Volume (ml)', 'Pack']][:5])

      Bottle Volume (ml)  Pack
595                  750    12
1889                 750    12
3616                1000    12
4422                 750    12
5022                 750    12


Code:

v = catStr_df[catStr_df['Item Number']==34881][['Bottle Volume (ml)', 'Pack']]\
.drop_duplicates(keep='first').to_dict()

v

Output:

{'Bottle Volume (ml)': {9534: 1000}, 'Pack': {9534: 12}}

Desired output:

{'Bottle Volume (ml)': 1000, 'Pack': 12}

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    采取不同的策略,这可行,但您需要获取列列表。这假设您希望索引号作为 dict 项

    def row_converter(row, listy):
        #convert pandas row to a dictionary
        #requires a list of columns and a row as a tuple
        count = 1
        pictionary = {}
        pictionary['Index'] = row[0]
        for item in listy:
            pictionary[item] = row[count]
            count += 1
        print(pictionary)
        return pictionary
    
    df = PD.read_csv("yourFile", dtype=object, delimiter=",", na_filter=False)
    listy = df.columns
    for row in df.itertuples():
        rowDict = row_converter(row, listy)
    

    【讨论】:

      【解决方案2】:

      尝试将.to_dict('records')[0] 添加到您想要的行

      catStr_df[catStr_df['Item Number']==34881].to_dict('records')[0]
      

      【讨论】:

      • @jpp 感谢您这么快回复我。当我尝试添加 [0] 时,我得到“KeyError:0”。更新:如果我把 drop_duplicates 去掉,你的建议就完美了,再次感谢你!
      • 所以catStr_df[catStr_df['Item Number']==34881].squeeze().to_dict()
      猜你喜欢
      • 2022-07-05
      • 2019-08-02
      • 1970-01-01
      • 2021-06-19
      • 2020-03-29
      • 2019-07-18
      • 2019-02-22
      • 2017-07-16
      相关资源
      最近更新 更多