<pandas, Python> 条件にあった行を削除する。
条件condition
にあった行Row
を削除drop
する。
まずは、お見本データフレームDataFrame
作成。
In [54]: data=''' ...: 1 2 3 4 5 ...: a b c d e ...: f g h i j ...: k l m n o ...: ''' In [55]: df = pd.read_table(io.StringIO(data), sep=' ') In [56]: df Out[56]: 1 2 3 4 5 0 a b c d e 1 f g h i j 2 k l m n o
で、行のドロップ。
インデックスindex
で指定すればよし。
In [58]: df.drop(1) Out[58]: 1 2 3 4 5 0 a b c d e 2 k l m n o In [59]: df.drop([1]) Out[59]: 1 2 3 4 5 0 a b c d e 2 k l m n o
で、列column
の場合はaxis=1
を指定。
In [61]: df.drop(['1'], axis=1) Out[61]: 2 3 4 5 0 b c d e 1 g h i j 2 l m n o
あとは、条件にあった行を見つける。
In [65]: df[['1', '3']].apply(lambda x: True if x[0] == 'f' and x[1] == 'h' else False, axis=1) Out[65]: 0 False 1 True 2 False dtype: bool In [66]: j = df[['1', '3']].apply(lambda x: True if x[0] == 'f' and x[1] == 'h' else False, axis=1) In [67]: j Out[67]: 0 False 1 True 2 False dtype: bool
で、True/False
のリストをデータフレームに突っ込めばオッケー。
In [68]: df[j] Out[68]: 1 2 3 4 5 1 f g h i j
が、、、こんな難しいことせんでも下記でよかった。。。
In [78]: df[(df['1'] == 'f') & (df['3'] == 'h')] Out[78]: 1 2 3 4 5 1 f g h i j