サンプル
In [23]: df = DataFrame(np.arange(20).reshape(5,4),
columns=[list('abcd')],
index=['one','two','three','four','five'])
In [24]: df
Out[24]:
a b c d
one 0 1 2 3
two 4 5 6 7
three 8 9 10 11
four 12 13 14 15
five 16 17 18 19
Dictionary記法、もしくは、Attribute記法でcolumnsを抽出
In [25]: df['a']
Out[25]:
one 0
two 4
three 8
four 12
five 16
Name: a, dtype: int64
In [26]: df[['a','c']]
Out[26]:
a c
one 0 2
two 4 6
three 8 10
four 12 14
five 16 18
In [27]: df.a
Out[27]:
one 0
two 4
three 8
four 12
five 16
Name: a, dtype: int64
一列だけ抽出した場合は、Seriesオブジェクトが返るが、あえてDataFrameとして取得する際は、次のように。
In [9]: df[['a']]
Out[9]:
a
one 0
two 4
three 8
four 12
five 16
Slicing記法を用いた場合は、rowsの抽出になる。
In [28]: df[0:2]
Out[28]:
a b c d
one 0 1 2 3
two 4 5 6 7
In [29]: df[3:]
Out[29]:
a b c d
four 12 13 14 15
five 16 17 18 19
Index指定でrowsを抽出する際は、ixフィールドを利用する
In [33]: df.ix['one']
Out[33]:
a 0
b 1
c 2
d 3
Name: one, dtype: int64
In [34]: df.ix['four':]
Out[34]:
a b c d
four 12 13 14 15
five 16 17 18 19
ixフィールドは、rowsとcolumnsの抽出が可能
In [35]: df.ix['one':'three',['b','d']]
Out[35]:
b d
one 1 3
two 5 7
three 9 11
In [36]: df.ix[:,['a','d','c']]
Out[36]:
a d c
one 0 3 2
two 4 7 6
three 8 11 10
four 12 15 14
five 16 19 18行単位で処理する方法(lineには1行を表すSeriesオブジェクトが入る)
In [43]: for index, line in df.iterrows():
print index
print line
....:
one
a 0
b 1
c 2
d 3
Name: one, dtype: int64
two
a 4
b 5
c 6
d 7
Name: two, dtype: int64
(以下略)
rowsのシャッフル
In [45]: df.reindex(np.random.permutation(df.index))
Out[45]:
a b c d
five 16 17 18 19
three 8 9 10 11
one 0 1 2 3
two 4 5 6 7
four 12 13 14 15