在for循环中排除不同的列

时间:2019-10-29 03:14:26

标签: python pandas

我正在编写一个循环,其中每个循环中我都希望从data中排除某些列。例如,第一个循环不包含x,第二个循环不包含x&y,第三个循环不包含x&y&z。这可能吗/最简单的解决方案是什么?

for c in ["x","x"&"y","x"&"y"&"z"]:
    print(data.loc[:, data.columns != c])

数据:

        y     c1372     c5244  ...            x         y     z
1   0.028292 -0.058234 -0.037606  ...         0         0   205.6
2   0.165635  0.256138  0.151508  ...         0         0   211.5
3   0.183923  0.171580  0.175374  ...         1         0   249.6
4   0.022088 -0.013564 -0.101703  ...         0         1   300.0
5  -0.151817  0.075051  0.159244  ...         0         0   306.7
6   0.339450  0.213238  0.241306  ...         0         0   263.5
7   0.157235  0.178404  0.255837  ...         1         0   370.0
8  -0.024312 -0.023970  0.009638  ...         0         1   433.0
9   0.002836 -0.024721  0.021513  ...         0         0   422.6
10  0.181220  0.155019  0.274975  ...         0         0   423.8
11  0.149472  0.094751  0.194383  ...         1         0   508.0
12 -0.038536 -0.095078 -0.051442  ...         0         1   589.9
13 -0.024252 -0.058521 -0.013778  ...         0         0   567.6
14  0.148980  0.178733  0.188664  ...         0         0   554.0
15  0.103337  0.095121  0.158011  ...         1         0   643.0
16  0.027118  0.021383  0.011049  ...         0         1   713.0
17  0.003271 -0.009936  0.033870  ...         0         0   732.6
18  0.106625  0.160375  0.167086  ...         0         0   735.0
19  0.093675  0.008717  0.052582  ...         1         0   817.7
20 -0.020589  0.002763  0.035459  ...         0         1   898.0
21 -0.014196 -0.028694  0.011052  ...         0         0   879.7
22  0.272170  0.348475  0.254698  ...         0         0   867.3
23  0.089336  0.040760  0.068140  ...         1         0  1138.6
24 -0.019957 -0.023532 -0.021013  ...         0         1  1245.0
25 -0.004846 -0.023470  0.014300  ...         0         0  1220.4
26  0.125502  0.069990  0.067689  ...         0         0  1214.5
27  0.087163  0.027069  0.036068  ...         1         0  1376.9
28 -0.029246  0.008492  0.005794  ...         0         1  1502.3
29 -0.012622 -0.025764 -0.021671  ...         0         0  1459.0

2 个答案:

答案 0 :(得分:0)

您可以

for c in [["x"],["x","y"],["x","y","z"]]:
    print(data.drop(c,axis=1))

答案 1 :(得分:0)

您可以简单地执行以下操作:

my_loops_cols = ["x", "y", "z"]
for i in range(1, len(my_loops_cols) + 1):
    exclude_cols = my_loops_cols[:i]
    # code to exlude the columns