【问题标题】:Turn dataframe into dictionary of row series将数据框转换为行系列字典
【发布时间】:2020-03-29 22:36:07
【问题描述】:

我需要在一个非常大的数据帧(1000 万 x 70)上进行迭代(不可能进行矢量操作)。 df.iterrows 并使用 df.loc[i, col] 直接访问数据帧太慢了。在过去,我会首先将数据框转换为字典字典,这使我可以非常快速地进行迭代。但是,这种方法占用了大量内存,对于我当前的数据不再可行。

我需要牺牲一些查找速度来节省内存。做这个的最好方式是什么?将我的数据框变成行系列 {index: Series} 的字典有用吗?

【问题讨论】:

  • 有什么特别的原因为什么您希望它们作为一个系列而不是一个字典或命名元组?
  • 您能否提供示例输出/输入,我尝试根据您的需求给出答案。
  • 将行转换为系列几乎肯定是个坏主意。我们可以为此获得更多背景信息吗?您的数据是什么样的?
  • 我在问题中添加了一些上下文。要点是 i dict of dict 占用了太多内存。

标签: python pandas dataframe dictionary iteration


【解决方案1】:

你的意思是这样的:

In [1112]: pd.DataFrame(df.reset_index().to_dict(orient='records'))                                                                                                                                        
Out[1112]: 
   index  id  block check
0      0   6     25   yes
1      1   6     32    no
2      2   9     18   yes
3      3  12     17    no
4      4  15     23   yes
5      5  15     11   yes
6      6  15     15   yes

In [1113]: df.reset_index().to_dict(orient='records')                                                                                                                                                      
Out[1113]: 
[{'index': 0, 'id': 6, 'block': 25, 'check': 'yes'},
 {'index': 1, 'id': 6, 'block': 32, 'check': 'no'},
 {'index': 2, 'id': 9, 'block': 18, 'check': 'yes'},
 {'index': 3, 'id': 12, 'block': 17, 'check': 'no'},
 {'index': 4, 'id': 15, 'block': 23, 'check': 'yes'},
 {'index': 5, 'id': 15, 'block': 11, 'check': 'yes'},
 {'index': 6, 'id': 15, 'block': 15, 'check': 'yes'}]

【讨论】:

    【解决方案2】:

    您可以这样做(感谢@oppressionslayer 的示例df):

    df
    
       id  block check
    0   6     25   yes
    1   6     32    no
    2   9     18   yes
    3  12     17    no
    4  15     23   yes
    5  15     11   yes
    6  15     15   yes
    
    df.to_dict('index')
    

    输出:

    {0: {'id': 6, 'block': 25, 'check': 'yes'}, 1: {'id': 6, 'block': 32, 'check': 'no'}, 2: {'id': 9, 'block': 18, 'check': 'yes'}, 3: {'id': 12, 'block': 17, 'check': 'no'}, 4: {'id': 15, 'block': 23, 'check': 'yes'}, 5: {'id': 15, 'block': 11, 'check': 'yes'}, 6: {'id': 15, 'block': 15, 'check': 'yes'}}
    

    如果您特别(出于某种原因)希望它是{index:series},您可以这样做,可以以相同的方式访问(即df_name[i][col]

    df.T.to_dict('series')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      • 2022-07-05
      • 2022-06-15
      • 1970-01-01
      相关资源
      最近更新 更多