【问题标题】:How to preserve column names while importing data using numpy?使用 numpy 导入数据时如何保留列名?
【发布时间】:2013-04-15 16:23:57
【问题描述】:

我正在使用 Python 中的 numpy 库将 CSV 文件数据导入到 ndarray 中,如下所示:

data = np.genfromtxt('mydata.csv', 
                     delimiter='\,', dtype=None, names=True)

结果提供以下列名称:

print(data.dtype.names)

('row_label',
 'MyDataColumn1_0',
 'MyDataColumn1_1')

原来的列名是:

row_label, My-Data-Column-1.0, My-Data-Column-1.1

NumPy 似乎在强制我的列名采用 C 风格的变量名格式。然而在很多情况下,我的 Python 脚本需要根据列名访问列,因此我需要确保列名保持不变。为此,NumPy 需要保留原始列名,否则我需要将列名转换为 NumPy 使用的格式。

  • 有没有办法在导入过程中保留原始列名?

  • 如果没有,是否有一种简单的方法可以将列标签转换为使用NumPy 正在使用的格式,最好使用一些NumPy 函数?

【问题讨论】:

标签: python numpy


【解决方案1】:

如果你设置names=True,那么你的数据文件的第一行会通过这个函数:

validate_names = NameValidator(excludelist=excludelist,
                               deletechars=deletechars,
                               case_sensitive=case_sensitive,
                               replace_space=replace_space)

这些是您可以提供的选项:

excludelist : sequence, optional
    A list of names to exclude. This list is appended to the default list
    ['return','file','print']. Excluded names are appended an underscore:
    for example, `file` would become `file_`.
deletechars : str, optional
    A string combining invalid characters that must be deleted from the
    names.
defaultfmt : str, optional
    A format used to define default field names, such as "f%i" or "f_%02i".
autostrip : bool, optional
    Whether to automatically strip white spaces from the variables.
replace_space : char, optional
    Character(s) used in replacement of white spaces in the variables
    names. By default, use a '_'.

也许您可以尝试提供自己的deletechars 字符串,它是一个空字符串。但是你最好修改并传递这个:

defaultdeletechars = set("""~!@#$%^&*()-=+~\|]}[{';: /?.>,<""")

只需从该集合中取出句号和减号,并将其传递为:

np.genfromtxt(..., names=True, deletechars="""~!@#$%^&*()=+~\|]}[{';: /?>,<""")

以下是来源: https://github.com/numpy/numpy/blob/master/numpy/lib/_iotools.py#l245

【讨论】:

  • 我很欣赏直接链接相关源代码并为 deletechars 添加一个更好的替代空字符串。就像你建议的那样工作。谢谢!
  • 不客气,很高兴它适用于您的情况。您可能知道这一点,但是在未来,如果您可以尝试使列名更简单并避免常见的禁止字符,您的代码将会更加健壮。
猜你喜欢
  • 2016-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
  • 1970-01-01
  • 2017-08-02
  • 2020-09-14
相关资源
最近更新 更多