gpt4 book ai didi

python - 在 pandas 数据框中查找每行的两个列列表中哪一个是真的最快方法

转载 作者:太空狗 更新时间:2023-10-30 01:06:00 26 4
gpt4 key购买 nike

我正在寻找执行以下操作的最快方法:

我们有一个 pd.DataFrame:

df = pd.DataFrame({
'High': [1.3,1.2,1.1],
'Low': [1.3,1.2,1.1],
'High1': [1.1, 1.1, 1.1],
'High2': [1.2, 1.2, 1.2],
'High3': [1.3, 1.3, 1.3],
'Low1': [1.3, 1.3, 1.3],
'Low2': [1.2, 1.2, 1.2],
'Low3': [1.1, 1.1, 1.1]})

看起来像:

In [4]: df
Out[4]:
High High1 High2 High3 Low Low1 Low2 Low3
0 1.3 1.1 1.2 1.3 1.3 1.3 1.2 1.1
1 1.2 1.1 1.2 1.3 1.2 1.3 1.2 1.1
2 1.1 1.1 1.2 1.3 1.1 1.3 1.2 1.1

我想知道的是 High1、High2、High3 浮点值中第一个大于或等于 High 值的。如果没有,应该是np.nan

对于 Low1、Low2、Low3 值也是如此,但在这种情况下,它们中的哪一个是第一个小于或等于 High 值的。如果没有,应该是np.nan

最后我需要知道哪一个,低或高先来。

解决这个问题的一种方法是一种奇怪且不太高效的方法是:

df['LowIs'] = np.nan
df['HighIs'] = np.nan

for i in range(1,4):
df['LowIs'] = np.where((np.isnan(df['LowIs'])) & (
df['Low'] >= df['Low'+str(i)]), i, df['LowIs'])
df['HighIs'] = np.where((np.isnan(df['HighIs'])) & (
df['High'] <= df['High'+str(i)]), i, df['HighIs'])

df['IsFirst'] = np.where(
df.LowIs < df.HighIs,
'Low',
np.where(df.LowIs > df.HighIs, 'High', 'None')
)

这给了我:

In [8]: df
Out[8]:
High High1 High2 High3 Low Low1 Low2 Low3 LowIs HighIs IsFirst
0 1.3 1.1 1.2 1.3 1.3 1.3 1.2 1.1 1.0 3.0 Low
1 1.2 1.1 1.2 1.3 1.2 1.3 1.2 1.1 2.0 2.0 None
2 1.1 1.1 1.2 1.3 1.1 1.3 1.2 1.1 3.0 1.0 High

由于我必须在高/低不同的许多迭代中一遍又一遍地执行此操作,因此执行此操作时的性能是关键。

所以我不介意 High1、High2、High3 和 Low1、Low2、Low3 是在一个单独的 DataFrame 中转置还是在字典中或其他什么。因此,以任何能够提供最佳性能的方式准备数据的过程可能会很慢而且很笨拙。

我曾研究过但无法以矢量化方式完成工作并且看起来也很慢的一个解决方案是:

df.loc[(df.index == 0), 'HighIs'] = np.where(
df.loc[(df.index == 0), ['High1', 'High2', 'High3']] >= 1.3
)[1][0] + 1

因此检查第一行中哪一列为真,然后查看 np.where() 的索引号。

期待任何建议,希望能学到新东西! :)

最佳答案

如果我没理解错的话,这是一个半向量化的版本:

df = pd.DataFrame({
'High': [1.3,1.7,1.1],
'Low': [1.3,1.2,1.1],
'High1': [1.1, 1.1, 1.1],
'High2': [1.2, 1.2, 1.2],
'High3': [1.3, 1.3, 1.3],
'Low1': [1.3, 1.3, 1.3],
'Low2': [1.2, 1.2, 1.2],
'Low3': [1.1, 1.1, 1.1]})

highs = ['High{:d}'.format(x) for x in range(0,4)]

for h in highs[::-1]:
mask = df['High'] <= df[h]
df.loc[mask, 'FirstHigh'] = h

产生:

   High  High1  High2  High3  Low  Low1  Low2  Low3 FirstHigh
0 1.3 1.1 1.2 1.3 1.3 1.3 1.2 1.1 High3
1 1.7 1.1 1.2 1.3 1.2 1.3 1.2 1.1 NaN
2 1.1 1.1 1.2 1.3 1.1 1.3 1.2 1.1 High1

解释:这里的关键是我们反向迭代列。也就是说,我们从 High3 开始,检查它是否大于 High,并相应地设置 FirstHigh。然后我们继续High2。如果这也更大,我们简单地覆盖以前的结果,如果不是,它会简单地保持原样。由于我们以相反的顺序迭代,结果是 第一个 更高的列将作为最终结果。

关于python - 在 pandas 数据框中查找每行的两个列列表中哪一个是真的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40746761/

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