2 回答
TA贡献1830条经验 获得超9个赞
di只要您查找只有 2 的行,此方法就可以适用于任意数量的列True,假设您有di_pos某处的列表
list_pos = [30, 40, 60, 90] # [d1_pos ,d2_pos ...
# Use `filter`, `diff` and `values` to get all the values of the columns di_test at once
arr_bool = (df.filter(like='d').diff() !=0).values
#create a mask where the sum in each row is equal to 2
mask = arr_bool.sum(1) == 2
#get the values in the rows using the list list_pos and the mask
arr_val = list_pos *arr_bool[mask]
#create the column result using
df.loc[mask,'result'] = df.loc[mask,'force']/(arr_val[arr_val .nonzero()][1::2] -
arr_val [arr_val .nonzero()][0::2])
print (df)
length force d1 d2 d3 d4 result
0 1.0 5000 300 300 300 300 NaN
1 1.2 5000 300 300 300 300 NaN
2 1.4 5000 300 300 300 300 NaN
3 1.6 2000 500 300 100 300 66.666667
4 1.8 2000 600 300 200 300 66.666667
5 2.0 3500 500 300 300 300 116.666667
6 2.2 3500 300 300 300 300 NaN
7 2.4 3500 100 300 300 300 NaN
8 2.5 1500 100 400 200 300 75.000000
9 2.6 1500 200 300 200 300 150.000000
10 3.0 6000 200 200 200 100 120.000000
添加回答
举报