Python 在 Pandas 数据帧第 2 列中找到低于阈值的第一次出现,并使用 NumPy 在同一行返回第 1 列值

问题描述 投票:0回答:2

我有一个数据框如下:

0.1   0.65
0.2   0.664
0.3   0.606
0.4   0.587
0.5   0.602
0.6   0.59
0.7   0.53

我必须在第 2 列中找到低于 0.6 的第一次出现,并返回同一行上第 1 列的值。在该示例中,返回值将为 0.4

我如何使用 NumpySciPy 来做到这一点?

代码是:

import pandas as pd

df = pd.DataFrame([*zip([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7], [0.65, 0.664, 0.606 ,0.587 ,0.602,0.59,0.53])])

threshold = 0.6
var = df[df[1] < threshold].head(1)[0]
res = var.iloc[0]
    
python pandas dataframe numpy scipy
2个回答
1
投票

您可以使用掩码和

df.head()
函数来获取给定阈值的第一次出现。

df[df[1] < threshold].head(1)[0]

3    0.4
Name: 0, dtype: float64

更新

要使用numpy,您需要将pandas转换为numpy并使用

np.where

array = df.values

array[np.where(array[:,1] < 0.6)][0,0]
0.4

为了比较性能,我们将对两组代码进行计时。

# Pandas style
def function1(df):
    return df[df[1] < threshold].head(1)[0]

# Numpy style
def function2(df):
    array = df.values

    return array[np.where(array[:,1] < 0.6)][0,0]

%timeit function1(df)
322 µs ± 6.71 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit function2(df)
11.8 µs ± 209 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

0
投票
import numpy as np


import pandas as pd

df = pd.DataFrame([*zip([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7], [0.65, 0.664, 0.606 ,0.587 ,0.602,0.59,0.53])])
print(df)
"""
     0      1
0  0.1  0.650
1  0.2  0.664
2  0.3  0.606
3  0.4  0.587
4  0.5  0.602
5  0.6  0.590
6  0.7  0.530
"""

threshold = 0.6
data = np.array(df)
index = np.argmax(data[:,1] < threshold)
#print(data[:,1])#[0.65  0.664 0.606 0.587 0.602 0.59  0.53 ]
#print(index)#3
# Extract the value from column 1 at that index
res = data[index,0]
print(res)#0.4
© www.soinside.com 2019 - 2024. All rights reserved.