我有一个如下所示的数据框:
Number Req Response
0 3 6
1 5 0
2 33 4
3 15 3
4 12 2
Run Code Online (Sandbox Code Playgroud)
我想在“请求”为 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)
Run Code Online (Sandbox Code Playgroud)
我收到“无效类型比较”错误。
我期望以下输出:
Min value of df['Response'] is: 0
Run Code Online (Sandbox Code Playgroud)
如果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
Run Code Online (Sandbox Code Playgroud)
细节:
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
Run Code Online (Sandbox Code Playgroud)
使用不匹配的值进行测试:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1098 次 |
| 最近记录: |