优化Pandas多索引查找

2024-03-29 01:22:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我用熊猫0.12.0。假设multi_df是一个具有多个索引的Pandas数据帧。我有一个元组(多个索引)的(长)列表,名为look_up_list。如果look_up_list中的元组在multi_df中,我想执行一个操作。在

下面是我的代码。有没有更快的方法来实现这一点?实际上len(multi_df)和{}相当大,所以我需要优化这一行:[multi_df.ix[idx]**2 for idx in look_up_list if idx in multi_df.index]。在

特别是,line_profiler告诉我连续检查:if idx in multi_df.index需要很长时间。在

import pandas as pd
df = pd.DataFrame({'id' : range(1,9),
                    'code' : ['one', 'one', 'two', 'three',
                                'two', 'three', 'one', 'two'],
                    'colour': ['black', 'white','white','white',
                            'black', 'black', 'white', 'white'],
                    'texture': ['soft', 'soft', 'hard','soft','hard',
                                        'hard','hard','hard'],
                    'shape': ['round', 'triangular', 'triangular','triangular','square',
                                        'triangular','round','triangular']
                    },  columns= ['id','code','colour', 'texture', 'shape'])
multi_df = df.set_index(['code','colour','texture','shape']).sort_index()['id']

# define the list of indices that I want to look up for in multi_df
look_up_list = [('two', 'white', 'hard', 'triangular'),('five', 'black', 'hard', 'square'),('four', 'black', 'hard', 'round') ] 
# run a list comprehension
[multi_df.ix[idx]**2 for idx in look_up_list if idx in multi_df.index]

注意:列表理解中的实际操作不是multi_df.ix[idx]**2,而是类似于:a_slow_function(multi_df.ix[idx])。在


Tags: indfforindextriangularmultilistblack
1条回答
网友
1楼 · 发布于 2024-03-29 01:22:32

可能使用multi_df.loc[look_up_list].dropna()。在

import pandas as pd
df = pd.DataFrame(
    {'id': range(1, 9),
     'code': ['one', 'one', 'two', 'three',
              'two', 'three', 'one', 'two'],
     'colour': ['black', 'white', 'white', 'white',
                'black', 'black', 'white', 'white'],
     'texture': ['soft', 'soft', 'hard', 'soft', 'hard',
                 'hard', 'hard', 'hard'],
     'shape': ['round', 'triangular', 'triangular', 'triangular', 'square',
               'triangular', 'round', 'triangular']
     }, columns=['id', 'code', 'colour', 'texture', 'shape'])
multi_df = df.set_index(
    ['code', 'colour', 'texture', 'shape']).sort_index()['id']

# define the list of indices that I want to look up for in multi_df
look_up_list = [('two', 'white', 'hard', 'triangular'), (
    'five', 'black', 'hard', 'square'), ('four', 'black', 'hard', 'round')]

subdf = multi_df.loc[look_up_list].dropna()
print(subdf ** 2)

收益率

^{pr2}$

注:

  • multi_df上面定义的是一个序列,而不是一个数据帧。我不 但你认为这会影响解决方案。在
  • 您在上面发布的代码引发了IndexingError: Too many indexers 所以我在猜测代码的意图。在

相关问题 更多 >