pandas:如何通过选择列范围来过滤行?

问题描述 投票:1回答:2

我有以下数据框:

    name  c1 c2 c3 c4 c5 c6 c7 c8 
    ---   -- -- -- -- -- -- -- --
0   img1  0  1  1  0  0  0  1  0
1   img2  1  0  0  0  0  0  1  1
2   img3  1  0  0  1  0  1  0  0
...

我想选择在列范围c2至c6中具有至少一个非零值(即1)的行。结果数据帧应排除第二行(img2 ...)。

我可以通过在条件下分别提及各列来解决此问题:

df = df[((df['c2']==1) | (df['c3']==1) ... | (df['c6']==1))]

是否还有其他更整洁的方式来实现相同的目的而无需提及每列(可能基于列的位置范围?)?

python pandas dataframe
2个回答
2
投票
# test data
from io import StringIO
data = StringIO('''name,c1,c2,c3,c4,c5,c6,c7,c8
img1,0,1,1,0,0,0,1,0
img2,1,0,0,0,0,0,1,1
img3,1,0,0,1,0,1,0,0''')

import pandas as pd
df = pd.read_csv(data)


# list of columns to be used

# select using column name
# cols = ['c{}'.format(i) for i in range(2,7)]

# select using column number
cols = df.columns[2:7]

# select if any col is 1
df = df[(df[cols]==1).any(axis=1)]



print(df)

   name  c1  c2  c3  c4  c5  c6  c7  c8
0  img1   0   1   1   0   0   0   1   0
2  img3   1   0   0   1   0   1   0   0

1
投票

您可以这样做:

df[df.ix[:,2:7].eq(1).any(axis=1)].ix[:,2:7] 

输出(由于全零而缺少第1行):

   c2  c3  c4  c5  c6
0   1   1   0   0   0
2   0   0   1   0   1

显示所有列:

df[df.ix[:,2:7].eq(1).any(axis=1)] 

输出:

   name  c1  c2  c3  c4  c5  c6  c7  c8
0  img1   0   1   1   0   0   0   1   0
2  img3   1   0   0   1   0   1   0   0
© www.soinside.com 2019 - 2024. All rights reserved.