假设我有一个包含N个多值分类列的数据帧,我希望使用Pandas尽可能快地对它们进行编码。你知道吗
这就是我迄今为止所取得的成就,但我不确定这是否是并行化熊猫的最佳方法(我更希望在可能的情况下采用矢量化方法):
def encode_single_categorical(input_series):
encoded_categorical_feature_data_frame = input_series.str.join(
'|').str.get_dummies().astype(
pd.np.bool).add_prefix(
input_series.name + '_')
return encoded_categorical_feature_data_frame
def encode_multi_valued_categorical_features(input_data_frame, categorical_features):
with Pool(cpu_count()) as p:
encoded_categorical_data_frames = p.map(encode_single_categorical,
[input_data_frame[categorical_feature] for
categorical_feature in categorical_features])
return pd.concat(encoded_categorical_data_frames, axis=1)
我还添加了一个测试,但这里的重点是方法。解决方案在功能上起作用,更多的是一个关于“这是熊猫的最佳实践吗?”?你知道吗
def test_encode_multi_valued_categorical_features(self):
categorical_features = ['productCategories', 'productTypes']
input_data_frame = pd.DataFrame({'querySource': ['source1', pd.np.nan, 'source3'],
'productTypes': [["t1", "t2", "t3"], ["t6", "t4", "t3"], ["t6", "t1"]],
'productBrand': ['brand1', 'brand2', 'brand3'],
'productCategories': [["c1", "c2", "c3"], ["c6", "c4", "c3"], ["c6", "c1"]],
})
expected_data_frame = pd.DataFrame({'querySource': ['source1', pd.np.nan, 'source3'],
'productBrand': ['brand1', 'brand2', 'brand3'],
'productCategories_c1': [True, False, True],
'productCategories_c2': [True, False, False],
'productCategories_c3': [True, True, False],
'productCategories_c4': [False, True, False],
'productCategories_c6': [False, True, True],
'productTypes_t1': [True, False, True],
'productTypes_t2': [True, False, False],
'productTypes_t3': [True, True, False],
'productTypes_t4': [False, True, False],
'productTypes_t6': [False, True, True],
})
result = utils.encode_multi_valued_categorical_features3(input_data_frame, categorical_features)
pd.testing.assert_frame_equal(result, expected_data_frame)
我建议您使用Pandas中内置的矢量化方法,这样读起来更干净,应该更快。你知道吗
下面是一个列的示例,您应该能够将其转换为函数并在所有相关列上循环。你知道吗
相关问题 更多 >
编程相关推荐