【问题标题】:Python script taking too long to run?Python 脚本运行时间过长?
【发布时间】:2018-07-02 15:31:23
【问题描述】:

我正在编写一个基本上执行以下操作的python脚本

  1. 将 CSV 文件作为数据框对象读取。
  2. 根据名称选择一些列并将它们存储在新的 DF 对象中。
  3. 对单元格中的值进行一些数学运算和字符串操作。我在这里使用 for 循环和 iterrows() 方法。
  4. 将修改后的 DF 写入 CSV
  5. 使用 for 循环将 CSV 写入 json。

这段代码需要很长时间才能运行。我试图理解为什么这需要这么长时间,以及我是否应该以不同的方式完成我的任务以加快执行速度。

import pandas
import json
import pendulum
import csv
import os
import time

start_time = time.time()
print("--- %s seconds ---" % (time.time() - start_time))

os.chdir('/home/csv_files_from_REC')
df11 = pandas.read_csv('RTP_Gap_2018-01-21.csv') ### Reads the CSV FILE

print df11.shape ### Prints the shape of the DF

### Filter the initial DF by selecting some columns based on NAME
df1 = df11[['ENODEB','DAY','HR','SITE','RTP_Gap_Length_Total_sec','RTP_Session_Duration_Total_sec','RTP_Gap_Duration_Ratio_Avg%']]

print df1.shape ## Prints Shape

#### Math and String manupulation stuff ###
for index, row in df1.iterrows():
    if row['DAY'] == 'Total':
        df1.drop(index, inplace=True)
    else:
        stamp = row['DAY'] + ' ' + str(row['HR']) + ':00:00'
        sitename = str(row['ENODEB'])+'_'+row['SITE']
        if row['RTP_Session_Duration_Total_sec'] == 0:
            rtp_gap = 0
        else:
            rtp_gap = row['RTP_Gap_Length_Total_sec']/row['RTP_Session_Duration_Total_sec']
        time1 = pendulum.parse(stamp,tz='America/Chicago').isoformat()
        df1.loc[index,'DAY'] = time1
        df1.loc[index,'SITE'] = sitename
        df1.loc[index,'HR'] = rtp_gap

### Write DF to CSV ###
df1.to_csv('RTP_json.csv',index=None)
json_file_ind = 'RTP_json.json'
file = open(json_file_ind, 'w')
file.write("")
file.close()

#### Write CSV to JSON ###
with open('RTP_json.csv', 'r') as csvfile:
    reader_ind = csv.DictReader(csvfile)
    row=[]
    for row in reader_ind:         
        row["RTP_Gap_Length_Total_sec"] = float(row["RTP_Gap_Length_Total_sec"])
        row["RTP_Session_Duration_Total_sec"] = float(row["RTP_Session_Duration_Total_sec"])
                row["RTP_Gap_Duration_Ratio_Avg%"]=float(row["RTP_Gap_Duration_Ratio_Avg%"])
        row["HR"] = float(row["HR"])
        with open('RTP_json.json', 'a') as json_file_ind:
            json.dump(row, json_file_ind)
            json_file_ind.write('\n')

 end_time = time.time()
 print("--- %s seconds ---" % (time.time() - end_time))

输出

    --- 2018-01-23T12:25:07.411691-06:00 seconds ---### START TIME
    (2055, 36) ### SIZE of initial DF
    (2055, 7) ### Size of Filtered DF
    --- 2018-01-23T12:31:54.480568-06:00 seconds --- --- ### END TIME

【问题讨论】:

  • 是的,index, row in df1.iterrows() 本质上会很慢,此外,您的循环内操作(如删除单个索引)会导致多项式运行时间。分配给循环中的各个行,例如df.loc[index, <whatever>] = 'foo' 会很慢。
  • 这里时间计算有误。应该是start_time - end_time
  • 致力于获取准确的时间戳。
  • 是json想要的结果行吗?
  • 这个不需要通过IMO迭代

标签: python pandas csv


【解决方案1】:

这篇文章应该会显着加快您的数据帧计算速度

import numpy as np

df1 = df11[['ENODEB','DAY','HR','SITE','RTP_Gap_Length_Total_sec','RTP_Session_Duration_Total_sec','RTP_Gap_Duration_Ratio_Avg%']]

print df1.shape ## Prints Shape

df1 = df1[df1.DAY != 'Total'].reset_index()
df1['DAY'] = pendulum.parse(df1['DAY'] + ' ' + str(df1['HR']) + ':00:00',tz='America/Chicago').isoformat()
df1['SITE'] = str(df1['ENODEB'])+'_'+df1['SITE']
df1['HR'] = np.where(df1['RTP_Session_Duration_Total_sec']==0,0,df1['RTP_Gap_Length_Total_sec']/df1['RTP_Session_Duration_Total_sec'])

另外,为什么还要写一个 csv 并再次读取它。

将 df 转换为 json 格式

format_json =  df1.to_json(orient='records') # converts df to json list
json_file_ind = 'RTP_json.json'
file = open(json_file_ind, 'w')
for i in format_json:
    file.write(i)
    file.write('\n')

这应该会显着加快您的代码速度

【讨论】:

  • 是的,这似乎帮了很多忙。现在使用 pendulum 解析时看到下面的错误。 df1['DAY'] = pendulum.parse(df1['DAY'],tz='America/Chicago') 文件 "/home/User/anaconda2/lib/python2.7/site-packages/pendulum/parser.py ",第 75 行,解析 ValueError:Series 的真值是不明确的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
  • 这是一个警告。错误使代码停止运行
  • 看起来在 pandas 中使用 pendulum 有更多好处 - stackoverflow.com/questions/47849342/…
猜你喜欢
  • 1970-01-01
  • 2017-05-01
  • 2019-02-12
  • 1970-01-01
  • 2016-11-14
  • 1970-01-01
  • 2020-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多