将数据读取到numpy数组

时间:2018-02-11 11:54:06

标签: python string pandas numpy int

我有一个文件

label,feature
0,70 80 90 50 33 58 ...
2,53 56 84 56 25 12 ...
1,32 56 84 89 65 87 ...
...
2,56 48 57 56 99 22 ...
4,25 65 84 54 54 15 ...

我希望数据可以

Ytrain = [0,2,1,...2,4]  (int, ndarray)
Xtrain = [[70 80 90 50 33 58...],
          [53 56 80 56 25 12...],
          ...
          [25 65 84 54 54 15...]] (int, ndarray)

这是我的代码

data = pd.read_csv('train.csv')
Ytrain = np.array(data.iloc[:, 0]).astype(int)
train = np.array(data.iloc[:, 1:]).astype(str)

Xtrain = []
for i in range(len(train)):
    tmp = [int(x) for x in train[i][0].split()]
    Xtrain.append(tmp)
Xtrain = np.array(Xtrain)

你有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

使用header=Noneskiprows=1read_csv添加多个分隔符,以便不读取csv标头:

data = pd.read_csv('train.csv', sep="[,\s+]", header=None, skiprows=1, engine='python')
print (data)
   0   1   2   3   4   5   6
0  0  70  80  90  50  33  58
1  2  53  56  84  56  25  12
2  1  32  56  84  89  65  87
3  2  56  48  57  56  99  22
4  4  25  65  84  54  54  15

最后由iloc选择:

Ytrain = data.iloc[:,0].values
Xtrain = data.iloc[:,1:].values

expand=True使用split DataFrame

data = pd.read_csv('train.csv')
Ytrain = data.iloc[:,0].values.astype(int)
Xtrain = data.iloc[:,1].str.split(expand=True).values.astype(int)

print (Ytrain)
[0 2 1 2 4]

print (Xtrain)
[[70 80 90 50 33 58]
 [53 56 84 56 25 12]
 [32 56 84 89 65 87]
 [56 48 57 56 99 22]
 [25 65 84 54 54 15]]

答案 1 :(得分:0)

您可以使用numpy。由于您有多个分隔符,因此需要做更多的工作。

import numpy as np

s = open('train.csv', 'r').read().replace(',', ' ')
arr = np.genfromtxt(s)

Ytrain = arr[:, 1]
Xtrain = arr[:, 1:]