根据pandas中多列的值从Dataframe中选择行

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

这个问题与anotherthisone这两个问题非常相关,我甚至会在这个问题上使用非常有用的解决方案中的例子。以下是已接受的解决方案(信用证到unutbu)的示例:

import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split(),
                   'C': np.arange(8), 'D': np.arange(8) * 2})
print(df)
#      A      B  C   D
# 0  foo    one  0   0
# 1  bar    one  1   2
# 2  foo    two  2   4
# 3  bar  three  3   6
# 4  foo    two  4   8
# 5  bar    two  5  10
# 6  foo    one  6  12
# 7  foo  three  7  14

print(df.loc[df['A'] == 'foo'])

产量

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

但是我想拥有A的所有行,只有B中的箭头中有'两个'。我试图尝试

print(df.loc[df['A']) & df['B'] == 'two'])

不幸的是,这不起作用。任何人都可以提出一种方法来实现这样的东西吗?如果解决方案有点普遍,那将是一个很大的帮助,例如,列A不具有相同的值,即'foo',但具有不同的值,并且您仍然需要整个列。

python pandas
3个回答
3
投票

我想我理解你修改过的问题。在B条件下进行子选择后,您可以选择所需的列,例如:

In [1]: df.loc[df.B =='two'][['A', 'B']]
Out[1]: 
     A    B
2  foo  two
4  foo  two
5  bar  two

例如,如果我想连接列A的所有字符串,其中列B的值为'two',那么我可以这样做:

In [2]: df.loc[df.B =='two'].A.sum()  # <-- use .mean() for your quarterly data
Out[2]: 'foofoobar'

您还可以groupby列B的值,并从一个表达式获得每个不同B组的串联结果:

In [3]: df.groupby('B').apply(lambda x: x.A.sum())
Out[3]: 
B
one      foobarfoo
three       barfoo
two      foofoobar
dtype: object

要使用A过滤Bnumpy.logical_and

In [1]: df.loc[np.logical_and(df.A == 'foo', df.B == 'two')]
Out[1]: 
     A    B  C  D
2  foo  two  2  4
4  foo  two  4  8

3
投票

行子集:这不是你要找的吗?

df.loc[(df['A'] == 'foo') & (df['B'] == 'two')]

   A   B  C D
2 foo two 2 4
4 foo two 4 8

您还可以在末尾添加.reset_index()以从零开始初始化索引。


3
投票

很容易,如果你这样做

     df[['A','B']][df['B']=='two']

你会得到:

    A    B

2  foo  two
4  foo  two
5  bar  two

要过滤A和B:

    df[['A','B']][(df['B']=='two') & (df['A']=='foo')]

你得到:

        A    B
    2  foo  two
    4  foo  two

如果你想要所有列:

        df[df['B']=='two']

你会得到:

            A    B  C   D
        2  foo  two  2   4
        4  foo  two  4   8
        5  bar  two  5  10    
© www.soinside.com 2019 - 2024. All rights reserved.