<Python, pandas> 任意カラムでかつ任意行を選択する。
列column
を指定して、行index
をさらに指定する。
列を[]
で指定して、さらに行を[ 条件式 ]
で指定する。
In [1]: import pandas as pd In [5]: import numpy as np In [6]: df = pd.DataFrame(data=np.random.randn(10,2), columns=list('ab')) In [7]: df Out[7]: a b 0 1.977998 2.261500 1 -1.221862 1.590989 2 0.512956 0.348313 3 1.853236 1.301840 4 -0.053330 -0.038790 5 -0.179619 -1.018209 6 0.826708 -0.542021 7 -0.159362 0.888030 8 -0.389310 -0.468977 9 1.405564 0.092451 In [8]: df['a'][ df['b'] > 0 ] Out[8]: 0 1.977998 1 -1.221862 2 0.512956 3 1.853236 7 -0.159362 9 1.405564 Name: a, dtype: float64
だが、、この方法は何やら下記のようなメッセージが出る時がある。
A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
で、loc
を使う。
df.loc[ df['b'] > 0, 'a' ] Out[9]: 0 1.977998 1 -1.221862 2 0.512956 3 1.853236 7 -0.159362 9 1.405564 Name: a, dtype: float64
にゃるほど!
マニュアル。
Indexing and Selecting Data — pandas 0.17.0 documentation