我用熊猫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])
。在
可能使用
multi_df.loc[look_up_list].dropna()
。在收益率
^{pr2}$注:
multi_df
上面定义的是一个序列,而不是一个数据帧。我不 但你认为这会影响解决方案。在IndexingError: Too many indexers
所以我在猜测代码的意图。在相关问题 更多 >
编程相关推荐