2016-11-15 64 views
1

如何選擇包含特定列列中的數據的行,並刪除那些在這些特定列中根本沒有數據的行?保留在列表中有數據的行python

這是代碼,我到目前爲止有:

VC_sub_selection = final[final['VC'].isin(['ACTIVE', 'SILENT']) & final['Status'].isin(['Test'])] 

data_usage_months = list(data_usage_res.columns) 

這是該數據集

item VC  Status  Jun 2016 Jul 2016 
1  Active Test  Nan  1.0 
2  Silent Test  Nan  Nan 
3  Active Test  2.0  3.0 
4  Silent Test  5.0  Nan 

我想什麼來實現的例子是,項目1,3,4將留在數據集中,並且項目2將被刪除。所以適用的條件是:如果所有的月份都是Nan比下降行。

謝謝

的Jeroen

+0

@Ukimiku我已經編輯我的問題,是清楚了嗎? –

+0

究竟是什麼選擇標準,即爲什麼項目2下降? 「2016年6月」和「2016年7月」中至少有一項不是「Nan」? – Cleb

+0

如果所有月份都是楠比排行 –

回答

1

雖然Nickil的解決方案回答了這個問題,它沒有考慮到更多的日期欄可以在以後添加。因此,在未來的情況下,使用列的索引位置可能不足。

下面介紹不使用索引的解決方案,而它使用正則表達式查找日期列:

import pandas as pd 
import re 

# item VC  Status  Jun 2016 Jul 2016 
# 1  Active Test  Nan  1.0 
# 2  Silent Test  Nan  Nan 
# 3  Active Test  2.0  3.0 
# 4  Silent Test  5.0  Nan 

df = pd.DataFrame({'item': [1,2,3,4], 
        'VC': ['Active', 'Silent', 'Active', 'Silent'], 
        'Status': ['Test'] * 4, 
        'Jun 2016': [None, None, 2.0, 5.0], 
        'Jul 2016': [1.0, None, 3.0, None]}) 

regex_pattern = r'[a-zA-Z]{3}\s\d{4}' 

date_cols = list(filter(lambda x: re.search(regex_pattern, x), df.columns.tolist())) 

df_res = df.dropna(subset=date_cols, how='all') 

#  Jul 2016 Jun 2016 Status  VC item 
# 0  1.0  NaN Test Active  1 
# 2  3.0  2.0 Test Active  3 
# 3  NaN  5.0 Test Silent  4