gpt4 book ai didi

python - 如何根据数据框另一列中的条件在列中找到最小值?

转载 作者:太空狗 更新时间:2023-10-30 02:35:52 24 4
gpt4 key购买 nike

我有一个如下所示的数据框:

Number  Req Response 
0 3 6
1 5 0
2 33 4
3 15 3
4 12 2

我想在“请求”为 15 之前确定最小“响应”值。

我尝试了下面的代码:

min_val=[]
for row in range(len(df)):
#if the next row of 'Req' contains 15, append the current row value of'Response'
if(df[row+1].loc[df[row+1]['Req'] == 15]):
min_val.append(df['Response'].min())
else:
min_val.append(0)

我收到“无效类型比较”错误。

我希望得到以下输出:

Min value of df['Response'] is: 0

最佳答案

如果可能的值 15 不在数据中,请使用通用解决方案:

df = df.reset_index(drop=True)
out = df.loc[df.Req.eq(15)[::-1].cumsum().ne(0), 'Response'].sort_values()
print (out)
1 0
3 3
2 4
0 6
Name: Response, dtype: int64

print (next(iter(out), 'no match'))
0

详细信息:

print (df.Req.eq(15))
0 False
1 False
2 False
3 True
4 False
Name: Req, dtype: bool

print (df.Req.eq(15)[::-1])
4 False
3 True
2 False
1 False
0 False
Name: Req, dtype: bool

print (df.Req.eq(15)[::-1].cumsum())
4 0
3 1
2 1
1 1
0 1
Name: Req, dtype: int32

print (df.Req.eq(15)[::-1].cumsum().ne(0))
4 False
3 True
2 True
1 True
0 True
Name: Req, dtype: bool

使用不匹配的值进行测试:

print (df)
Number Req Response
0 0 3 6
1 1 5 0
2 2 33 4
3 3 150 3
4 4 12 2


df = df.reset_index(drop=True)
out = df.loc[df.Req.eq(15)[::-1].cumsum().ne(0), 'Response'].sort_values()
print (out)
Series([], Name: Response, dtype: int64)

print (next(iter(out), 'no match'))
no match

关于python - 如何根据数据框另一列中的条件在列中找到最小值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57693357/

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