【问题标题】:Get the column names of a python numpy array获取 python numpy 数组的列名
【发布时间】:2018-05-15 06:45:57
【问题描述】:

我有一个 csv 数据文件,其标题指示列名。

xy   wz  hi kq
0    10  5  6
1    2   4  7
2    5   2  6

我跑:

X = np.array(pd.read_csv('gbk_X_1.csv').values)

我想获取列名:

['xy', 'wz', 'hi', 'kg']

我读了这个post,但解决方案为我提供了无。

【问题讨论】:

  • np.genfromtxt() 和 names=True 选项可能会有所帮助。见stackoverflow.com/questions/12336234/…
  • 我觉得你需要pd.read_csv('gbk_X_1.csv').columns.tolist()
  • 您的问题是获取结构化数组还是从结构化数组中获取名称?如果是后者:list(x.dtype.fields).
  • 可以,也可以使用:X = np.genfromtxt('gbk_X_1.csv', dtype=float, delimiter=',', names=True) print(X.dtype.names)

标签: python arrays pandas numpy


【解决方案1】:

使用以下代码:

import re

f = open('f.csv','r')

alllines = f.readlines()
columns = re.sub(' +',' ',alllines[0]) #delete extra space in one line
columns = columns.strip().split(',') #split using space

print(columns)

假设 CSV 文件是这样的:

xy   wz  hi kq
0    10  5  6
1    2   4  7
2    5   2  6

【讨论】:

    【解决方案2】:

    让我们假设你的 csv 文件看起来像

    xy,wz,hi,kq
    0,10,5,6
    1,2,4,7
    2,5,2,6
    

    然后使用pd.read_csv 将文件转储到数据帧中

    df = pd.read_csv('gbk_X_1.csv')
    

    数据框现在看起来像

    df
    
       xy  wz  hi  kq
    0   0  10   5   6
    1   1   2   4   7
    2   2   5   2   6
    

    它的三个主要组成部分是

    • 数据,您可以通过values 属性访问它们

      df.values
      
      array([[ 0, 10,  5,  6],
             [ 1,  2,  4,  7],
             [ 2,  5,  2,  6]])
      
    • index,您可以通过index 属性访问它

      df.index
      
      RangeIndex(start=0, stop=3, step=1)
      
    • ,您可以通过columns 属性访问它们

      df.columns
      
      Index(['xy', 'wz', 'hi', 'kq'], dtype='object')
      

    如果要将列作为列表,请使用to_list 方法

    df.columns.tolist()
    
    ['xy', 'wz', 'hi', 'kq']
    

    【讨论】:

      猜你喜欢
      • 2011-11-25
      • 1970-01-01
      • 2019-02-08
      • 2017-05-12
      • 1970-01-01
      • 2017-05-03
      • 1970-01-01
      • 2021-07-10
      • 2021-02-15
      相关资源
      最近更新 更多