gpt4 book ai didi

python - np.genfromtxt 多个分隔符?

转载 作者:太空宇宙 更新时间:2023-11-04 07:58:24 24 4
gpt4 key购买 nike

我的文件是这样的:

1497484825;34425;-4,28,-14;-4,28,-14;-4,28,-14;-4,28,-14;-4,28,-14;-4,28,-14
1497484837;34476;-4,28,-14;-4,28,-14;-4,28,-14;-4,28,-14;-4,28,-14;-4,28,-14

我想使用 np.genfromtxt 将它导入到 numpy 数组中。最大的问题是它有';'和 ',' 作为分隔符。我的尝试:

import numpy as np
import io

s = io.StringIO(open('2e70dfa1.csv').read().replace(';',','))

data = np.genfromtxt(s,dtype=int,delimiter=',')

我得到错误:

TypeError: Can't convert 'bytes' object to str implicitly

如何解决?我也乐于接受全新的(更好的)想法。

最佳答案

根据docs :

Parameters:
fname : file, str, pathlib.Path, list of str, generator File, filename, list, or generator to read. If the filename extension is gz or bz2, the file is first decompressed. Note that generators must return byte strings in Python 3k. The strings in a list or produced by a generator are treated as lines.

给它一个生成器可能更容易也更有效,只是要记住它必须产生字节串:

>>> with open('2e70dfa1.csv', 'rb') as f:
... clean_lines = (line.replace(b';',b',') for line in f)
... data = np.genfromtxt(clean_lines, dtype=int, delimiter=',')
...
>>> data
array([[1497484825, 34425, -4, 28, -14,
-4, 28, -14, -4, 28,
-14, -4, 28, -14, -4,
28, -14, -4, 28, -14],
[1497484837, 34476, -4, 28, -14,
-4, 28, -14, -4, 28,
-14, -4, 28, -14, -4,
28, -14, -4, 28, -14]])

关于python - np.genfromtxt 多个分隔符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44757160/

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