2017-05-16 57 views
1

我有以下的DF,我想在列名应用过滤器,只是仍然是那些具有一定的字符串开头:过滤列数据帧以特定字符串开头

这是我现在的DF:

ruta2: 
      Current SAN Prev.1m SAN Prev.2m SAN Prev.3m SAN Current TRE \ 

A     5   6   7   6   3 
B     6   5   7   6   6 
C     12   11   11   11   8 

基本上我想是过滤数据帧,并保持与Current开头的列。

然后将所需的输出为:

ruta2: 
      Current SAN Current TRE 

A     5   3 
B     6   6 
C     12   8 

为了做到这一点,我想这过滤器,但输出值误差:

ruta2=ruta2[~(ruta2.columns.str[:4].str.startswith('Prev'))] 

回答

1

看来你只需要:

ruta2=ruta2.loc[:, ~(ruta2.columns.str[:4].str.startswith('Prev'))] 
#same as 
#ruta2=ruta2.loc[:, ~ruta2.columns.str.startswith('Prev')] 
print (ruta2) 
    Current SAN Current TRE 
A   5   3 
B   6   6 
C   12   8 

或者:

cols = ruta2.columns[ ~(ruta2.columns.str[:4].str.startswith('Prev'))] 
ruta2=ruta2[cols] 
print (ruta2) 
    Current SAN Current TRE 
A   5   3 
B   6   6 
C   12   8 

但是,如果只需要Current列使用filter^意味着正则表达式字符串的开始):

ruta2=ruta2.filter(regex='^Current') 
print (ruta2) 
    Current SAN Current TRE 
A   5   3 
B   6   6 
C   12   8 
0
#filter the columns names starting with 'Current' 
ruta2[[e for e in ruta2.columns if e.startswith('Current')]] 
Out[383]: 
    Current SAN Current TRE 
A   5   3 
B   6   6 
C   12   8 

或者你可以使用一个遮罩阵列来过滤列:

ruta2.loc[:,ruta2.columns.str.startswith('Current')] 
Out[385]: 
    Current SAN Current TRE 
A   5   3 
B   6   6 
C   12   8 
相关问题