2016-01-20 82 views
3

列所以我有一個Python 2.7熊貓數據幀包含大量列的一樣:Python的大熊貓過濾器由多個字符串

['SiteName', 'SSP', 'PlatformClientCost', 'rawmachinecost', 'rawmachineprice', 'ClientBid' +... + 20 more] 

而且我想排除所有列中包含的任何單詞「平臺」或'客戶'以下是我的嘗試:

col = [c for c in dataframe.columns if c.lower() not in ('platform','client') ] 
print col 
['SiteName', 'SSP', 'IONumber', 'userkey', 'Imps', 'PlatformClientCost', 'rawplatformcost', 'rawbidprice', 'PlatformClientBid', 'RawBidCPM', 'ClientBidCPM', 'CostCPM', 'ClientCostCPM', 'BidRatio'] 

我在網上找不到任何相關的解決方案,所以任何幫助將超級感激!

感謝, 威爾

回答

1

使用矢量化str.contains

In [222]: 
df = pd.DataFrame(columns=['SiteName', 'SSP', 'IONumber', 'userkey', 'Imps', 'PlatformClientCost', 'rawplatformcost', 'rawbidprice', 'PlatformClientBid', 'RawBidCPM', 'ClientBidCPM', 'CostCPM', 'ClientCostCPM', 'BidRatio']) 
df.columns 

Out[222]: 
Index(['SiteName', 'SSP', 'IONumber', 'userkey', 'Imps', 'PlatformClientCost', 
     'rawplatformcost', 'rawbidprice', 'PlatformClientBid', 'RawBidCPM', 
     'ClientBidCPM', 'CostCPM', 'ClientCostCPM', 'BidRatio'], 
     dtype='object') 

In [223]: 
df.columns[~df.columns.str.contains(r'platform|client', case=False)] 
​ 
Out[223]: 
Index(['SiteName', 'SSP', 'IONumber', 'userkey', 'Imps', 'rawbidprice', 
     'RawBidCPM', 'CostCPM', 'BidRatio'], 
     dtype='object') 

在這裏我們可以通過一個正則表達式模式和case=False所以你不需要lower在這裏,這將返回一個布爾面膜:

In [225]: 
df.columns.str.contains(r'platform|client', case=False) 

Out[225]: 
array([False, False, False, False, False, True, True, False, True, 
     False, True, False, True, False], dtype=bool) 

然後,我們將否定運算符~應用於反轉布爾掩碼並屏蔽列數組。

+0

太棒了!謝謝! –

1

這是一個很好的嘗試,但你有你的邏輯混淆的地方:

col = [c for c in dataframe.columns if c.lower() not in ('platform','client') ] 
print col 
['SiteName', 'SSP', 'IONumber', 'userkey', 'Imps', 'PlatformClientCost', 'rawplatformcost', 'rawbidprice', 'PlatformClientBid', 'RawBidCPM', 'ClientBidCPM', 'CostCPM', 'ClientCostCPM', 'BidRatio'] 

仔細查看你的病情。您僅排除名稱完全匹配的列(無論大小寫)「平臺」和「客戶端」。

你想要什麼是:

col = [c for c in dataframe.columns if 'platform' not in c.lower() and 'client' not in c.lower()] 
print col 
['SiteName', 'SSP', 'IONumber', 'userkey', 'Imps', 'rawbidprice', 'RawBidCPM', 'CostCPM', 'BidRatio'] 

使用熊貓方法EdChum的答案很可能是更有效的,如果是你重要的。

+0

儘管您的解決方案只需要最少的更改,但您認爲EdChum的效率更高。儘管如此,你也有我的感謝:)) –