gpt4 book ai didi

python - 基于 bool 掩码选择行 - 为什么性能存在差异?

转载 作者:太空宇宙 更新时间:2023-11-03 15:49:49 25 4
gpt4 key购买 nike

我一直在使用 pandas DataFrame 对象并根据列值选择行。我注意到,如果您首先使用 .values 选择行,那么它的速度大约是原来的两倍。为什么是这样?如果第一个示例速度较慢,您是否有任何理由应该使用它?

df = pd.DataFrame(np.random.randint(0, high=10, size=(1000, 4)), columns=['A', 'B', 'C', 'D'])

%timeit df_test = df[df['A'] == 9]
The slowest run took 4.98 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 363 µs per loop

%timeit df_test = df[df['A'].values == 9]
1000 loops, best of 3: 181 µs per loop

最佳答案

Pandas 掩码以系列或 DataFrame 的形式返回 bool 掩码。 Numpy 掩码以数组的形式返回一个 bool 值掩码。

将 bool 掩码映射到系列或数据帧比返回 bool 数组要花费一些时间。

换句话说,当您执行 df['A'] == 9 时,将掩码映射到索引并返回系列是额外的时间,否则它们将是相同的。

举例说明:

df['A'] == 9 

0 False
1 False
2 False
3 False
4 False
Name: A, dtype: bool

type(df['A'] == 9)
pandas.core.series.Series

df['A'].values == 9
array([False, False, False, False, False], dtype=bool)

type(df['A'].values == 9)
numpy.ndarray

那么为什么在 numpy 掩蔽速度更快时进行系列掩蔽?

假设你有一个索引以不同方式排序的数据框

df = pd.DataFrame(np.random.randint(0, high=10, size=(5, 4)), columns=list('ABCD'))

A B C D
0 4 9 1 5
1 8 6 5 0
2 5 5 9 5
3 2 5 7 5
4 1 1 7 2

df2 = pd.DataFrame(np.random.randint(0, high=10, size=(5, 4)), columns=list('ABCD'),index=[4,3,2,1,0])

A B C D
4 0 4 5 8
3 9 6 7 2
2 0 9 8 6
1 2 6 2 7
0 7 2 8 7

现在你想根据它们的索引值选择 df2A 列中有 4 的行

# If you do numpy masking 
df2.loc[df['A'].values==4] # First index will be selected no matter what the actual index is
A B C D
4 0 4 5 8

df2.loc[df['A']==4] # Row with that index will be selected
A B C D
0 7 2 8 7

不仅如此,在更多情况下,您还希望使用 indexcolumn 数据,因此需要使用系列掩码。希望能更好地解释事情。

关于python - 基于 bool 掩码选择行 - 为什么性能存在差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47608339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com