2016-12-04 57 views
1

我正在处理大量预测变量的数据集,并希望通过使用控制文件轻松测试不同的复合变量分组。对于初学者来说,控制文件会指示是否包含变量。这里有一个例子:如何根据另一个查找选择数据框中的列?

control = pd.DataFrame({'Variable': ['Var1','Var2','Var3'], 
        'Include': [1,0,1]}) 

control 
Out[48]: 
    Include Variable 
0  1  Var1 
1  0  Var2 
2  1  Var3 

data = pd.DataFrame({'Sample':['a','b','c'], 
        'Var1': [1,0,0], 
        'Var2': [0,1,0], 
        'Var3': [0,0,1]}) 

data 
Out[50]: 
    Sample Var1 Var2 Var3 
0  a  1  0  0 
1  b  0  1  0 
2  c  0  0  1 

所以处理后的结果应该是一个新的数据帧,它看起来像数据,但下降的VAR2柱:

data2 
Out[51]: 
    Sample Var1 Var3 
0  a  1  0 
1  b  0  0 
2  c  0  1 

我能得到这个通过使用选择性删除列的工作.itterows():

data2 = data.copy() 
for index, row in control.iterrows(): 
    if row['Include'] != 1: 
     z = (row['Variable']) 
     data2.drop(z, axis=1,inplace="True") 

这工作,但似乎应该有办法做到这一点对整个数据框中一次。例如:

data2 = data[control['Include'] == 1] 

但是,这会根据“包含”值而不是列过滤出行。

任何建议表示赞赏。

回答

2

选择从control框架必要的标头,并使用从data智能选择:

headers = control[control['Include']==1]['Variable'] 
all_headers = ['Sample'] + list(headers) 
data[all_headers] 
# Sample Var1 Var3 
#0  a  1  0 
#1  b  0  0 
#2  c  0  1 

一个侧面说明:如果可能的话可以考虑使用布尔TrueFalse,而不是在Include列0和1。转换头到列表第一的伎俩 -

+0

谢谢@DYZ是一个非常快速的解决方案。 在这种情况下测试布尔值的正确方法是什么?仍然== 1? – user1355179

+0

这是这样的:'headers = control [control ['Include']] ['Variable']' – DyZ

0

这应该使用numpy的重建

# get data columns values which is a numpy array 
dcol = data.columns.values 
# find the positions where control Include are non-zero 
non0 = np.nonzero(control.Include.values) 
# slice control.Variable to get names of Variables to include 
icld = control.Variable.values[non0] 
# search the column names of data for the included Variables 
# and the Sample column to get the positions to slice 
srch = dcol.searchsorted(np.append('Sample', icld)) 
# reconstruct the dataframe using the srch slice we've created 
pd.DataFrame(data.values[:, srch], data.index, dcol[srch]) 

enter image description here

+1

使用原始numpy例程的方法更加冗长,只是混淆了初学者;坚持更多的用户友好的熊猫索引例程(特别是因为标签不要求一个numpy soln) – Jeff

相关问题