Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将pandas read_csv调用传递到另一个具有命名参数的函数中_Python - Fatal编程技术网

Python 将pandas read_csv调用传递到另一个具有命名参数的函数中

Python 将pandas read_csv调用传递到另一个具有命名参数的函数中,python,Python,因为函数是Python的,所以我应该能够重构它: def get_事件(): csv_path=os.path.join(输入_csv_path,数据_NAME+'.csv') 打印(f'在{datetime.now()}'开始读取事件) start_time=datetime.now() 事件=pd.read\u csv(csv\u路径,数据类型=数据类型) end_time=datetime.now() 打印(f'Finished reading events at{end_time}({e

因为函数是Python的,所以我应该能够重构它:

def get_事件():
csv_path=os.path.join(输入_csv_path,数据_NAME+'.csv')
打印(f'在{datetime.now()}'开始读取事件)
start_time=datetime.now()
事件=pd.read\u csv(csv\u路径,数据类型=数据类型)
end_time=datetime.now()
打印(f'Finished reading events at{end_time}({end_time-start_time})})
返回事件
对这样的事情:

def get_事件():
csv_path=os.path.join(输入_csv_path,数据_NAME+'.csv')
events=\u time\u function\u call('reading events',pd.read\u csv,{'filepath\u或\u buffer':csv\u path,'dtype':DTYPES})
返回事件
定义时间函数调用(消息、函数、*kwargs):
打印(f'Starting{message}在{datetime.now()}'处)
start_time=datetime.now()
结果=函数(*kwargs)
end_time=datetime.now()
打印(f'Finished{message}在{end_time}({end_time-start_time})处)
返回结果
即,将pandas函数及其命名参数传递给helper函数。(注意,在传递函数时,我不确定如何传递命名参数,这是有帮助的。)

但是在重构之后,我得到了以下错误:

ValueError:无效的文件路径或缓冲区对象类型:


关于如何将函数及其命名参数传递到另一个Python函数进行求值,我缺少了什么?

您可能希望重构为:

def get_events():
    csv_path = os.path.join(INPUT_CSV_PATH, DATA_NAME + '.csv')
    events = _time_function_call('reading events', pd.read_csv, filepath_or_buffer=csv_path, dtype=DTYPES)
    return events

def _time_function_call(message, func, *args, **kwds):
    start_time = datetime.now()
    print(f'Starting {message} at {start_time}')
    result = func(*args, **kwds)
    end_time = datetime.now()
    duration = end_time - start_time
    print(f'Finished {message} at {end_time} ({duration})')
    return result
这样Python就可以处理这些问题

我建议使用和,因为这样的代码更容易编写,例如:

from time import perf_counter
import logging

logger = logging.getLogger(__name__)

class log_timer:
    def __init__(self, message):
        self.message = message

    def __enter__(self):
        logger.info(f"{self.message} started")
        # call to perf_counter() should be the last statement in method
        self.start_time = perf_counter()

    def __exit__(self, exc_type, exc_value, traceback):
        # perf_counter() call should be first statement
        secs = perf_counter() - self.start_time
        state = 'finished' if exc_value is None else 'failed'
        logger.info(f"{self.message} {state} after {secs * 1000:.2f}ms")
可以像这样使用:

from time import sleep

logging.basicConfig(
    format='%(asctime)s %(levelname)s %(message)s',
    level=0,
)

with log_timer("sleep"):
    sleep(1)
这样,您就不必担心将任意代码位转换为函数以及它们之间的线程状态


另外,使用
datetime
来测量少量代码的运行时间也不是很好,
time
模块提供了
perf_counter
,可以将其交给更合适的OS/CPU(更高分辨率)计时器。

谢谢,这很管用。我甚至可以从调用中删除恼人的
filepath\u或\u buffer=
(没有人命名该参数)。关于时间方面的问题,我会仔细考虑你的建议,这很有用。不幸的是,它可能只是一小行代码,但它们需要五分钟以上才能运行,所以低分辨率计时器是可以的。如果它需要那么长的时间,我会考虑在python之外将文件拆分成几个较小的文件,否则您可以使用类似或甚至类似的方法