gpt4 book ai didi

python - 修剪 numpy 数组中值的部分

转载 作者:行者123 更新时间:2023-12-01 09:02:42 25 4
gpt4 key购买 nike

我只想要数组中每个值的前 10 个字符。

这是数组:

array(['2018-06-30T00:00:00.000000000', '2018-06-30T00:00:00.000000000',
'2018-06-30T00:00:00.000000000', '2018-06-30T00:00:00.000000000',
'2018-06-30T00:00:00.000000000', '2018-06-30T00:00:00.000000000',
'2018-06-30T00:00:00.000000000', '2018-09-30T00:00:00.000000000']

我想编写代码来给我这个:

array(['2018-06-30','2018-06-30'   .... etc

这是一个更新:我的代码是:

x = np.array(df4['per_end_date'])
x

输出是:

array(['2018-06-30T00:00:00.000000000', '2018-06-30T00:00:00.000000000',
'2018-06-30T00:00:00.000000000', '2018-06-30T00:00:00.000000000',
'2018-06-30T00:00:00.000000000', '2018-06-30T00:00:00.000000000',
'2018-06-30T00:00:00.000000000', '2018-09-30T00:00:00.000000000',
'2018-09-30T00:00:00.000000000', '2018-09-30T00:00:00.000000000', etc

我只想要数组中每个值的前 10 个字符。以下代码给出错误 IndexError:标量变量的索引无效。

x = np.array([y[:9] for y in x])

最佳答案

虽然 numpy 并不总是操作字符串的最佳方式,但您可以向量化此操作,并且与往常一样,向量化函数应该优先于迭代。

设置

arr = np.array(['2018-06-30T00:00:00.000000000', '2018-06-30T00:00:00.000000000',
'2018-06-30T00:00:00.000000000', '2018-06-30T00:00:00.000000000',
'2018-06-30T00:00:00.000000000', '2018-06-30T00:00:00.000000000',
'2018-06-30T00:00:00.000000000', '2018-09-30T00:00:00.000000000'],
dtype='<U29')
<小时/>

使用np.frombuffer

np.frombuffer(
arr.view((str, 1 )).reshape(arr.shape[0], -1)[:, :10].tostring(),
dtype=(str,10)
)

array(['2018-06-30', '2018-06-30', '2018-06-30', '2018-06-30',
'2018-06-30', '2018-06-30', '2018-06-30', '2018-09-30'],
dtype='<U10')

时间

arr = np.repeat(arr, 10000)

%timeit np.array([y[:10] for y in arr])
48.6 ms ± 961 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
np.frombuffer(
arr.view((str, 1 )).reshape(arr.shape[0], -1)[:, :10].tostring(),
dtype=(str,10)
)

6.87 ms ± 311 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit np.array(arr,dtype= 'datetime64[D]')
44.9 ms ± 2.93 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

关于python - 修剪 numpy 数组中值的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52348939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com