根据列列表中的值选择行

2024-06-23 18:45:40 发布

您现在位置:Python中文网/ 问答频道 /正文

相关:Selecting with complex criteria from pandas.DataFrame

我有一些数据帧:

df = pd.DataFrame({'name': ['apple1', 'apple2', 'apple3', 'apple4', 'orange1', 'orange2', 'orange3', 'orange4'], 
                   'A': [0, 0, 0, 0, 0, 0 ,0, 0], 
                  'B': [0.10, -0.15, 0.25, -0.55, 0.50, -0.51, 0.70, 0], 
                  'C': [0, 0, 0.25, -0.55, 0.50, -0.51, 0.70, 0.90],
                  'D': [0.10, -0.15, 0.25, 0, 0.50, -0.51, 0.70, 0.90]})
df
name    A   B   C   D
0   apple1  0   0.10    0.00    0.10
1   apple2  0   -0.15   0.00    -0.15
2   apple3  0   0.25    0.25    0.25
3   apple4  0   -0.55   -0.55   0.00
4   orange1 0   0.50    0.50    0.50
5   orange2 0   -0.51   -0.51   -0.51
6   orange3 0   0.70    0.70    0.70
7   orange4 0   0.00    0.90    0.90

现在让我们假设我想选择ABCD中值小于0.25的所有行:

df[(df['A'] < 0.25) & 
  (df['B'] < 0.25) &
  (df['C'] < 0.25) &
  (df['D'] < 0.25)]
    name    A   B   C   D
0   apple1  0   0.10    0.00    0.10
1   apple2  0   -0.15   0.00    -0.15
3   apple4  0   -0.55   -0.55   0.00
5   orange2 0   -0.51   -0.51   -0.51

很好,但是使用列列表作为输入可以实现同样的效果吗?

想象一下,我想过滤100列而不是4列


Tags: namedataframedfwithorange3criteriacomplexapple1
2条回答

在这种情况下,由于您在多个列上具有相同的条件,因此可以使用^{}over axis=1检查所选列的条件是否为True

df[df.loc[:, 'A':].lt(0.25).all(axis=1)]

      name  A     B     C     D
0   apple1  0  0.10  0.00  0.10
1   apple2  0 -0.15  0.00 -0.15
3   apple4  0 -0.55 -0.55  0.00
5  orange2  0 -0.51 -0.51 -0.51

如果列的顺序不太好,请使用双括号选择数据:

df[df[['A', 'B', 'C', 'D']].lt(0.25).all(axis=1)]

注:^{}<相同,代表lessthan”


如果您有很多单字母列,手动选择太多,我们可以使用DataFrame.filterregex

df[df.filter(regex='[A-Z]').lt(0.25).all(axis=1)]

使用^{}axis=1来执行^{}

df[(df[['A','B','C','D']]<0.25).all(axis=1)]

输出

      name  A     B     C     D
0   apple1  0  0.10  0.00  0.10
1   apple2  0 -0.15  0.00 -0.15
3   apple4  0 -0.55 -0.55  0.00
5  orange2  0 -0.51 -0.51 -0.51

另一种方法:^{}

df[df[df.columns.difference(['name'])].lt(0.25).all(axis=1)]

相关问题 更多 >

    热门问题