2016-04-12 15 views
3

私はパンダのデータフレーム内の特定の列を列名に基づいてフィルタリングしようとしています。パンダデータフレームの特定の列をフィルタリングする

ので、フレームはおおよそ次のとおりです。

import pandas as pd 

dict_build = {'Var_1_Reading': [1,2,3,10,0.1], 'Var_1_Confidence':[1,1,1,1,1], 'Var_2_Reading': [1,2,3,10,0.1], 'Var_2_Confidence':[1,1,1,1,1]} 
df = pd.DataFrame(dict_build) 

は、私が最後にConfidenceの列をドロップします。私はfilterで試したが、うまくいかなかった。現時点では、私はやっている:

ColList_to_drop = df.filter(regex='Confidence', axis=1).columns.values 
filtered_df = df.drop(ColList_to_drop, axis = 1) 

私はこれらの2つのステップをすべて正規表現で行うことができますか?

答えて

2

これはそれを行う必要があります。

>>> cols = [col for col in df.columns if not col.endswith('Confidence')]  
>>> df = df[cols] 

>>> df 
    Var_1_Reading Var_2_Reading 
0   1.0   1.0 
1   2.0   2.0 
2   3.0   3.0 
3   10.0   10.0 
4   0.1   0.1 
2

をあなたはnegative lookahead assertion(?!...)を使用することができます。

print df.filter(regex='^(?!.*Confidence).*$') 
    Var_1_Reading Var_2_Reading 
0   1.0   1.0 
1   2.0   2.0 
2   3.0   3.0 
3   10.0   10.0 
4   0.1   0.1 
1

あなたのように、直接カラムインデックスにstrのメソッドを使用することができます。

df.loc[:, df.columns.str.endswith('Confidence')] 
関連する問題