gpt4 book ai didi

python - 使用 numpy.genfromtxt 读取包含逗号的字符串的 csv 文件

转载 作者:行者123 更新时间:2023-11-30 09:23:17 26 4
gpt4 key购买 nike

我正在尝试使用 numpy.genfromtxt 读取 csv 文件,但某些字段是包含逗号的字符串。字符串用引号括起来,但 numpy 无法将引号识别为定义单个字符串。例如,对于“t.csv”中的数据:

2012, "Louisville KY", 3.5
2011, "Lexington, KY", 4.0

代码

np.genfromtxt('t.csv', delimiter=',')

产生错误:

ValueError: Some errors were detected ! Line #2 (got 4 columns instead of 3)

我正在寻找的数据结构是:

array([['2012', 'Louisville KY', '3.5'],
['2011', 'Lexington, KY', '4.0']],
dtype='|S13')

查看文档,我没有看到任何处理此问题的选项。有没有办法用 numpy 来实现它,或者我只需要使用 csv 模块读取数据,然后将其转换为 numpy 数组?

最佳答案

您可以使用pandas (成为在科学Python中处理数据框(异构数据)的默认库)。这是read_csv可以处理这个。来自文档:

quotechar : string

The character to used to denote the start and end of a quoted item. Quoted items 
can include the delimiter and it will be ignored.

默认值为"。示例:

In [1]: import pandas as pd

In [2]: from StringIO import StringIO

In [3]: s="""year, city, value
...: 2012, "Louisville KY", 3.5
...: 2011, "Lexington, KY", 4.0"""

In [4]: pd.read_csv(StringIO(s), quotechar='"', skipinitialspace=True)
Out[4]:
year city value
0 2012 Louisville KY 3.5
1 2011 Lexington, KY 4.0

这里的技巧是,您还必须使用 skipinitialspace=True 来处理逗号分隔符后面的空格。

除了强大的 csv 阅读器之外,我还强烈建议将 pandas 与您拥有的异构数据一起使用(您给出的 numpy 中的示例输出都是字符串,尽管您可以使用结构化数组)。

关于python - 使用 numpy.genfromtxt 读取包含逗号的字符串的 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25945696/

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