『Pandas』数据读取&DataFrame切片

读取文件

numpy.loadtxt()

import numpy as np

dataset_filename = "affinity_dataset.txt"

X = np.loadtxt(dataset_filename)

n_samples, n_features = X.shape
print("This dataset has {0} samples and {1} features".format(n_samples, n_features))
This dataset has 100 samples and 5 features

pandas.read_csv()

import pandas as pd

dataset_filename = "affinity_dataset.txt"

Xp = pd.read_csv(dataset_filename, delimiter=' ', names=list('abcde'))

print(Xp.shape)
(100, 5) 

检测一下输出,

print(X[:5])
print(Xp[:5])
print(type(Xp['a'][0]))
[[ 0.  0.  1.  1.  1.]
 [ 1.  1.  0.  1.  0.]
 [ 1.  0.  1.  1.  0.]
 [ 0.  0.  1.  1.  1.]
 [ 0.  1.  0.  0.  1.]]
   a  b  c  d  e
0  0  0  1  1  1
1  1  1  0  1  0
2  1  0  1  1  0
3  0  0  1  1  1
4  0  1  0  0  1
<class 'numpy.int64'>

DF.loc索引

当每列已有column name时,用 df [ 'a' ] 就能选取出一整列数据。如果你知道column names和index,且两者都很好输入,可以选择 .loc,

print(Xp.loc[0, 'a'], '
' ,
      Xp.loc[0:3, ['a', 'b']], '
' ,
      Xp.loc[[1, 5], ['b', 'c']])
0 
   a  b
0  0  0
1  1  1
2  1  0
3  0  0 
   b  c
1  1  0
5  1  0

DF.iloc索引

如果我们嫌column name太长了,输入不方便,有或者index是一列时间序列,更不好输入,那就可以选择 .iloc了。这边的 i 我觉得代表index,比较好记点。

print(Xp.iloc[1,1],'
',
      Xp.iloc[0:3, [0,1]],'
',  
      Xp.iloc[[0, 3, 5], 0:2]  )
1 
    a  b
0  0  0
1  1  1
2  1  0 
    a  b
0  0  0
3  0  0
5  0  1

DF.ix索引

.ix 的功能就更强大了,它允许我们混合使用下标和名称进行选取。 可以说它涵盖了前面所有的用法。基本上把前面的都换成df.ix 都能成功,但是有一点,就是

df.ix [ [ ..1.. ], [..2..] ],  1框内必须统一,必须同时是下标或者名称,2框也一样。 BTW, 1框是用来指定row,2框是指定column。

原文地址:https://www.cnblogs.com/hellcat/p/7476854.html