在Python中向for循环中的列添加元素

时间:2018-05-20 17:12:18

标签: python loops

我在迭代列时尝试使用追加到数组的值来添加值。所以我想要它,以便z = 0,它填充'bubblelife'中的第0列,然后当z = 1开始时,它填充第1列。

我使用两个for循环逐行扫描(使用索引变量i)并使用索引变量z移动到下一列。

导入的excel文件的格式如下所示,第一列用于日期戳,另外4列用于数据。

3/26/2018 0:01  0   94.98629761 99.9942627  0
3/26/2018 0:18  0   94.98629761 0   0
3/26/2018 0:18  94.99441528 94.98629761 99.9942627  64.99035645
3/26/2018 0:36  89.9921875  94.98629761 95.99212646 0
3/26/2018 0:36  89.9921875  94.98629761 0   94.98666382

我试图在状态从0变为非零值时获取时间数据,反之亦然,以计算状态保持ON的时间长度(速度保持非零的时间长度)。

我在这一行收到错误:

 bubblelife[:,z].append(time[i])

完整代码:

import os
import numpy as np
import pandas as pd
import datetime

file = 'RackTime.xlsx'
x1=pd.read_excel(file, sheet_name="Dataset1")
time = x1.iloc[:,0]
racklife = x1.iloc[:,1:5]
bl_racklife = racklife !=0                                                      


bubblelife=[];prematurebreak=[]; 
np_bubblelife = np.array(bubblelife); np_prematurebreak = np.array(prematurebreak)
for z in range(0,3):
    for i in range(1, len(bl_racklife)):
            if (bl_racklife.iloc[i-1,z]!=bl_racklife.iloc[i,z] ):
                 bubblelife[:,z].append(time[i])
            if bl_racklife.iloc[i-2,z]!= bl_racklife.iloc[i-1,z] and bl_racklife.iloc[i,z]!= bl_racklife.iloc[i-1,z]:
                 np_prematurebreak[:,z].append(time[i-1])

期望的结果: 数组'bubblelife'包含四列时间数据

3/26/2018 0:18  3/26/2018 2:22  3/26/2018 0:18  3/26/2018 0:18
3/26/2018 1:29  3/26/2018 2:40  3/26/2018 0:36  3/26/2018 0:36
3/26/2018 1:47  3/26/2018 3:15  3/26/2018 0:54  3/26/2018 2:58
3/26/2018 2:04  3/26/2018 3:33  3/26/2018 2:04  3/26/2018 4:44
3/26/2018 3:51  3/26/2018 3:51  3/26/2018 2:22  3/26/2018 7:06
3/26/2018 4:08  3/26/2018 4:08  3/26/2018 2:40  3/26/2018 7:59
3/26/2018 5:02  3/26/2018 5:02  3/26/2018 2:58  3/26/2018 8:16
3/26/2018 5:19  3/26/2018 5:55  3/26/2018 3:15  3/26/2018 8:34
3/26/2018 5:37  3/26/2018 6:12  3/26/2018 3:33  3/26/2018 10:20

0 个答案:

没有答案