python - 获取 Numpy genfromtxt 转换器以使用 def 函数

标签 python numpy genfromtxt

我在论坛上搜索过,似乎无法解决以下问题。我对 python 很陌生,有一点编程经验,所以我的问题可能很微不足道。

想要使用date.strptime类方法将日期时间字符串转换为日期时间格式。

问题是列中的字符串格式不一致(大多数是%Y-%m-%d $H:$M:$S.%f);当时间正好是秒时,毫秒小数被省略(格式应改为 %Y-%m-%d $H:$M:$S)。当strptime遇到无法识别的格式时,它只会在数组元素中放置一个None值。

有没有办法在lambda函数中创建异常(即ValueError异常),如果没有,如何将字符串值传递到“正常” “genfromtxt 转换器选项中的 def timeConv(x) 函数?

也许有更好的方法来解决这个问题......?

当格​​式为 %Y-%m-%d $H:$M:$S 时,我当前的代码会产生 None 值:

timeConv = lambda x: datetime.strptime(x, '\"%Y-%m-%d $H:$M:$S.%f\"')

Time = np.genfromtxt(file, dtype='object', delimiter=',', skip_header=4, usecols=(0), converters = {0: timeConv})

最佳答案

您可以使用 try.. except 首先尝试一种格式,如果不起作用,则捕获异常并尝试另一种格式:

import datetime as DT
import numpy as np

def timeConv(x):
    try:
        return DT.datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f')
    except ValueError as err:
        return DT.datetime.strptime(x, '%Y-%m-%d %H:%M:%S')

time = np.genfromtxt(file, dtype='object', delimiter=',', skip_header=4,
                     usecols=(0), converters = {0: timeConv})

函数 timeConv 以与传递 lambda 相同的方式传递给 genfromtxt


dateutil module有一个日期字符串解析器,它不需要您指定日期字符串的确切格式。所以使用 dateutil 你可以简单地写

import dateutil.parser as dparser
import numpy as np

time = np.genfromtxt(file, dtype='object', delimiter=',', skip_header=4,
                     usecols=(0), converters = {0: dparser.parse})

请注意,虽然 dparser.parse 非常易于使用,但存在一些不明确的日期字符串,例如 2013-8-9(8 月 8 日或 9 月 9 日?)需要更多的照顾。请务必阅读 dayfirstyearfirst 参数,以便您可以控制解析器的行为。

关于python - 获取 Numpy genfromtxt 转换器以使用 def 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15840614/

相关文章:

python - 为什么 True 在 numpy 数组中打印前导空格

python - Numpy,从文件中读取,没有分隔符但固定模式

python - 我收到此 ValueError : total size of new array must be unchanged error. 任何人都可以解决吗?

python - 用于性能、缓存的 Numpy 纯函数

python - 遍历用户输入和列表

python - 读取文件并连接numpy数组中的两列

python - genfromtxt 中的值太多,无法解压

python - 脚本中的 UTF 8 不匹配

python-3.x - 将一维数组转换为 Numpy 中的行或列向量

python - 计算两个数平方和的平方根的最有效方法是什么?