假设我们有一个pandas数据帧df
,其列为'A'
,以及下面的非向量化转换函数:
def transform_a_to_b(a):
...
return b
然后,如果我们想要使用'A'
上的转换创建列'B'
,我们可以执行以下操作:
df['B'] = df['A'].apply(lambda x: transform_a_to_b(a))
如果转换花费的时间不是很多,列'A'
中有许多重复的值,并且转换总是将重复的a值映射到相同的b值,那么执行此操作的更好方式是什么?另外,假设数据框中有更多列,因此我确实希望将这些值映射回原始数据框中的每一行.
我想出了下面的解决方案,但我觉得应该有更简单的东西.
transform_counts = 0
def transform_a_to_b(a):
global transform_counts
# Keep count of how many times this was called
transform_counts += 1
return 2 * a
# Test dataframe with several duplicates
df = pd.DataFrame({
'A': [1, 3, 2, 2, 3, 3, 2, 3, 1, 1, 1],
})
# My solution:
# Perform transformation only 3 times for the 3 unique A values and preserve order
df = df.merge(
df['A'].drop_duplicates().apply(lambda a: pd.Series(
data=[a, transform_a_to_b(a)],
index=['A', 'B'],
)),
on='A',
how='left',
)
函数transform_counts
为3
且df如下所示:
A B
0 1 2
1 3 6
2 2 4
3 2 4
4 3 6
5 3 6
6 2 4
7 3 6
8 1 2
9 1 2
10 1 2
我不反对缓存,如果这是最简单的,但我不能更改原始的转换定义.