【问题标题】:How to append values to array via for-loop如何通过for循环将值附加到数组
【发布时间】:2020-02-27 06:23:09
【问题描述】:

我有三组 np.arrays。第二个是我的数据集(U 和 t),第三个是每个数据点的数量(iarray)。我正在尝试创建三个新数组:一个包含一定间隔内的(U)的值。第二个包含归因于 (U) 值的 (t) 值。第三个包含原始数组中这些值的数量(对于 U 和 t,它们应该相同)。

我为新的 U 和 t 获得了两个不同大小的数组,而我的整数数组只包含一个值。

所有的尺寸都应该相同。

我尝试设置一系列 for 循环来检查 U 的值是否在某个时间间隔内。然后检查 t 中的值是否接近添加到新 t 数组中的最后一个点。如果一切顺利,它应该将原始数组中具有相同整数的值附加到新数组中的相同位置。

数据数组和数字数组

t = a[:,0]
U = a[:,1]
iarray=np.array(range(len(t)))

代码核心

tpeak = np. array([])
Upeak = np. array([])
b=np.array([])

for i in range(len(t)):
    if (np.size(b)==0) and 0.9<U[i]and U[i]<4 :
        tpeak=np.append(tpeak,t[i])

for i in range(len(t)):
    if (np.size(b)==0) and 0.9<U[i]and U[i]<4 :
       Upeak=np.append(Upeak,U[i])

for i in range(len(t)):
    if (np.size(b)==0) and 0.9<U[i]and U[i]<4 :
       b=np.append(b,iarray[i])

for i in range(len(t)):
    if U[i]>1 and U[i]<4  and 0.8<tpeak[-1]-t[i] : 
        tpeak=np.append(tpeak,t[i])

for i in range(len(t)):
    if U[i]>1 and U[i]<4  and 0.8<tpeak[-1]-t[i] :
        Upeak=np.append(Upeak,U[i])


for i in range(len(t)):
    if U[i]>1 and U[i]<4  and 0.8<tpeak[-1]-t[i] : 
        b=np.append(b,iarray[i])

如前所述,我希望输出是三个大小相同的数组(Upeak、tpeak 和 b),但 U peak 比 tpeak 小 1,而 ipeak 仅包含一个值。

【问题讨论】:

  • 你能展示一个a的小样本吗?以及您的预期输出?
  • 感谢您的快速回复!是的,我很快就会这样做。我的朋友给我展示了一个更优雅的独奏,我也可以在这里展示。

标签: python arrays for-loop if-statement append


【解决方案1】:

我不明白你的问题是什么,顺便说一下,你可以使用 list comprenshion,这样你的代码会更清晰。 而不是:

tpeak = np. array([])
Upeak = np. array([])
b=np.array([])

for i in range(len(t)):
    if (np.size(b)==0) and 0.9<U[i]and U[i]<4 :
        tpeak=np.append(tpeak,t[i])

for i in range(len(t)):
    if (np.size(b)==0) and 0.9<U[i]and U[i]<4 :
       Upeak=np.append(Upeak,U[i])

for i in range(len(t)):
    if (np.size(b)==0) and 0.9<U[i]and U[i]<4 :
        b=np.append(b,iarray[i])

 for i in range(len(t)):
    if U[i]>1 and U[i]<4  and 0.8<tpeak[-1]-t[i] : 
        tpeak=np.append(tpeak,t[i])

for i in range(len(t)):
    if U[i]>1 and U[i]<4  and 0.8<tpeak[-1]-t[i] :
        Upeak=np.append(Upeak,U[i])


for i in range(len(t)):
    if U[i]>1 and U[i]<4  and 0.8<tpeak[-1]-t[i] : 
        b=np.append(b,iarray[i])

你可以使用:

tpeak=[t[i] if (np.size(b)==0) and 0.9<U[i]and U[i]<4 for i in range(len(t)):]

或者尝试优化 for 循环。

for i in range(len(t)):
    ...

因为如您所见,您将这段代码重复了 6 次以上。 如果您向我们展示这段代码的输出将会非常棒,这样我们就可以更好地帮助您。

【讨论】:

    猜你喜欢
    • 2021-07-01
    • 2021-05-19
    • 2021-11-07
    • 2020-04-25
    • 1970-01-01
    • 2015-01-13
    • 2015-04-27
    • 2019-04-12
    • 2016-01-31
    相关资源
    最近更新 更多