pandas-dataframe-append在附加数百个Dataframe(每个Dataframe有数千行)时速度很慢

doinxwow  于 2021-06-15  发布在  Cassandra
关注(0)|答案(0)|浏览(363)

下面代码中的变量“data”包含数百个查询数据库的执行结果。每个执行结果是一天的数据,包含大约7000行数据(列是timestamp和value)。我每天互相追加数据,结果产生数百万行数据(这几百个追加需要很长时间)。当我有了一个传感器的完整数据集后,我将这些数据作为一列存储在unitdfDataframe中,然后对每个传感器重复上述过程,并将它们全部合并到unitdfDataframe中。
我相信追加和合并都是代价高昂的操作。我可能找到的唯一可能的解决方案是将每一列拆分为列表,一旦所有数据都添加到列表中,就将所有列合并到一个数据框中。有什么加速的建议吗?

i = 0
for sensor_id in sensors: #loop through each of the 20 sensors
    #prepared statement to query Cassandra
    session_data = session.prepare("select  timestamp, value from measurements_by_sensor where unit_id = ? and sensor_id = ? and date = ? ORDER BY timestamp ASC")
    #Executing prepared statement over a range of dates    
    data = execute_concurrent(session, ((session_data, (unit_id, sensor_id, date)) for date in dates), concurrency=150, raise_on_first_error=False)

    sensordf = pd.DataFrame()
    #Loops through the execution results and appends all successful executions that contain data
    for (success, result) in data:
        if success:
          sensordf = sensordf.append(pd.DataFrame(result.current_rows))

    sensordf.rename(columns={'value':sensor_id}, inplace=True) 
    sensordf['timestamp'] = pd.to_datetime(sensordf['timestamp'], format = "%Y-%m-%d %H:%M:%S", errors='coerce')
    if i == 0:
        i+=1
        unitdf = sensordf
    else:
        unitdf = unitdf.merge(sensordf, how='outer')

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题