如何根据另一列中的符号变化来计算列表中的数学差异



我有一个大列表,如下所示:

515.20320783       0.05658324
516.20360241       0.03486690
517.20399699       0.02094333
518.20439157       0.02199200
519.20478615       0.03610312
520.20518073       0.05240170
521.20557530       0.05834678
522.20596988       0.04893050
523.20636446       0.02992211
524.20675904       0.01215849
525.20715362       0.00224414
526.20754820      -0.00168170
527.20794277      -0.00608658
528.20833735      -0.01532678
529.20873193      -0.02889651
530.20912651      -0.04376070
531.20952109      -0.05776619
532.20991567      -0.07066846
533.21031024      -0.08255477
534.21070482      -0.09145077
535.21109940      -0.09284463
536.21149398      -0.08325564

我首先需要根据第2列值的符号变化来分离第1列的两个列表,这意味着第1列中所有在第2列中对应值为正的值都应该在一个列表中,而第2列的值为负的值应该在另一个列表。然后我想计算子列表(之前创建的列表(的第一项和最后一项之间的差异。我所做的工作如下,但它似乎不正确

import numpy as np
l = [f for f in sorted(os.listdir('.')) if f.startswith('config')]
maxnum = np.max([int(os.path.splitext(f)[0].split('_')[1]) for f in l])
l = ['configuration_%d.out' % i for i in range(maxnum)]
meand = []
meands=[]
for i, d in enumerate (CASES):
a = np.loadtxt(os.path.join(root, directory,d)).T
y = a[1]
x = a[0]
mig = np.abs(a[5])
theta = a[3]
s = a[2]
h = min(y)+6
t = max(y)-6
meand = []
for i in range(1,len(y)):
if h <y[i]<t :
idx = np.where(np.diff(np.sign(theta)) != 0)[0] + 1

meand_length = s[idx]-s[idx-1]


meand.append(meande_length)
meands.append(np.mean(meand))

print(meands)

使用numpy方法signnonzero:

list1 = np.arange(0, 20, 2)
# array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18]
list2 = np.linspace(-1, 1, 10)
# ~ array([-1, -0.77, -0.55, -0.33, -0.11,  0.11,  0.33,  0.55,  0.77,  1.])
s = np.sign(list2)
# array([-1., -1., -1., -1., -1.,  1.,  1.,  1.,  1.,  1.])
idx_sign_change = np.nonzero(np.diff(s) != 0)[0]
# array([4])
split_lists = np.split(list1, idx_sign_change)
# [array([0, 2, 4, 6]), array([ 8, 10, 12, 14, 16, 18])]
diff = [l[-1] - l[0] for l in split_lists]
# [6, 10]
mean_diff = np.mean(diff)

请注意,如果有多个符号更改,这也会起作用。

最新更新