如何根据另一个中的查找选择数据框中的列?

时间:2016-12-04 05:54:32

标签: python pandas dataframe

我正在处理具有大量预测变量的数据集,并希望使用控制文件轻松测试不同的复合变量分组。对于初学者,控制文件将指示是否包含变量。这是一个例子:

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]

但是,这会根据' Include'过滤掉行。价值,而不是列。

任何建议表示赞赏。

2 个答案:

答案 0 :(得分: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

附注:如果可能,请考虑在True列中使用布尔FalseInclude而不是0和1。

答案 1 :(得分: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

相关问题