[英]Get the minimum value of a dataframe column with condition on another dataframe
[英]How to find minimum value in a column based on condition in an another column of a dataframe?
我有一個如下數據框:
Number Req Response
0 3 6
1 5 0
2 33 4
3 15 3
4 12 2
我想在'Req'為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
一種方法是使用idxmax
來查找Req
等於15
的第一個索引,使用結果索引數據幀並采用最小Response
:
df.loc[:df.Req.eq(15).idxmax(), 'Response'].min()
# 0
哪里:
df.Req.eq(15)
0 False
1 False
2 False
3 True
4 False
Name: Req, dtype: bool
並且idxmax
將返回第一個True
事件的索引,在本例中為3
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.