【问题标题】:DataFrame : Convert Rows to dict python?DataFrame:将行转换为 dict python?
【发布时间】:2020-10-23 11:11:48
【问题描述】:

我正在尝试将数据框行转换为字典。

df

       a            b
  
 0    paul         active
 1    marcus     inactive
 2    bruno        active
 3    scott      inactive
 4    anthony      active

到行中的字典:

final_dict = {'paul':'active','marcus':'inactive','bruno':'active','scott':'inactive','anthony':'active'}

【问题讨论】:

标签: python dataframe dictionary


【解决方案1】:

方法如下:

d = {k:df['b'][df[df['a']==k].index.values[0]] for k in df['a']}


分解一下,这里是如何在列中找到特定值的索引:

val = 'value' # The value we want to find the index of
col = 'a' # The column the value is in
index = df[df[col]==val].index.values[0] # Here is how to find the index

在给定索引的情况下,如何找到特定列的值:

index = 3 The index of the column we want to find the value of
col = 'a' # The column which want to find a value in
value = df[col][index] # Here is how to find the value

所以字典基本上会有a列的值和b列的值,我们通过索引找到与a中的值对应的值。

【讨论】:

    【解决方案2】:

    你可以用这个

    import pandas as pd
    df.to_dict(orient='records')
    

    您可以参考here

    【讨论】:

    • 这是一个漂亮的副本,已经有一个很好的答案,请删除您的帖子并标记问题。如果你保留你的答案,你会让下一个来到这里的人停止他们的研究并且不知道全部细节,谢谢
    猜你喜欢
    • 2021-11-06
    • 2017-01-28
    • 2018-10-14
    • 2017-03-03
    • 2021-07-16
    • 1970-01-01
    • 2022-01-08
    • 2017-05-18
    • 2013-12-28
    相关资源
    最近更新 更多