如何根据Pandas中某列的值从DataFrame中选择行?

在SQL中,我会使用:

SELECT *
FROM table
WHERE column_name = some_value

当前回答

在Pandas的更新版本中,受文档启发(查看数据):

df[df["colume_name"] == some_value] #Scalar, True/False..

df[df["colume_name"] == "some_value"] #String

通过将子句放在括号()中,并用&和|(和/或)组合来组合多个条件。这样地:

df[(df["colume_name"] == "some_value1") & (pd[pd["colume_name"] == "some_value2"])]

其他过滤器

pandas.notna(df["colume_name"]) == True # Not NaN
df['colume_name'].str.contains("text") # Search for "text"
df['colume_name'].str.lower().str.contains("text") # Search for "text", after converting  to lowercase

其他回答

您可以在函数中使用loc(方括号):

# Series
s = pd.Series([1, 2, 3, 4]) 
s.loc[lambda x: x > 1]
# s[lambda x: x > 1]

输出:

1    2
2    3
3    4
dtype: int64

or

# DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [10, 20, 30]})
df.loc[lambda x: x['A'] > 1]
# df[lambda x: x['A'] > 1]

输出:

   A   B
1  2  20
2  3  30

要添加:您还可以执行df.groupby('column_name').get_group('column_desired_value').reset_index()以生成具有特定值的指定列的新数据帧。例如。,

import pandas as pd
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split()})
print("Original dataframe:")
print(df)

b_is_two_dataframe = pd.DataFrame(df.groupby('B').get_group('two').reset_index()).drop('index', axis = 1) 
#NOTE: the final drop is to remove the extra index column returned by groupby object
print('Sub dataframe where B is two:')
print(b_is_two_dataframe)

运行此命令可以:

Original dataframe:
     A      B
0  foo    one
1  bar    one
2  foo    two
3  bar  three
4  foo    two
5  bar    two
6  foo    one
7  foo  three
Sub dataframe where B is two:
     A    B
0  foo  two
1  foo  two
2  bar  two

tl;博士

熊猫相当于

select * from table where column_name = some_value

is

table[table.column_name == some_value]

多种条件:

table[(table.column_name == some_value) | (table.column_name2 == some_value2)]

or

table.query('column_name == some_value | column_name2 == some_value2')

代码示例

import pandas as pd

# Create data set
d = {'foo':[100, 111, 222],
     'bar':[333, 444, 555]}
df = pd.DataFrame(d)

# Full dataframe:
df

# Shows:
#    bar   foo
# 0  333   100
# 1  444   111
# 2  555   222

# Output only the row(s) in df where foo is 222:
df[df.foo == 222]

# Shows:
#    bar  foo
# 2  555  222

在上面的代码中,是df[df.foo==222]行根据列值给出行,在本例中为222。

也可能出现多种情况:

df[(df.foo == 222) | (df.bar == 444)]
#    bar  foo
# 1  444  111
# 2  555  222

但在这一点上,我建议使用查询函数,因为它不那么冗长,并产生相同的结果:

df.query('foo == 222 | bar == 444')

在Pandas的更新版本中,受文档启发(查看数据):

df[df["colume_name"] == some_value] #Scalar, True/False..

df[df["colume_name"] == "some_value"] #String

通过将子句放在括号()中,并用&和|(和/或)组合来组合多个条件。这样地:

df[(df["colume_name"] == "some_value1") & (pd[pd["colume_name"] == "some_value2"])]

其他过滤器

pandas.notna(df["colume_name"]) == True # Not NaN
df['colume_name'].str.contains("text") # Search for "text"
df['colume_name'].str.lower().str.contains("text") # Search for "text", after converting  to lowercase

很好的答案。只有当数据帧的大小接近百万行时,许多方法在使用df[df['col']==val]时往往需要很长时间。我希望“another_column”的所有可能值都对应于“some_column“中的特定值(在本例中是在字典中)。这起作用很快。

s=datetime.datetime.now()

my_dict={}

for i, my_key in enumerate(df['some_column'].values): 
    if i%100==0:
        print(i)  # to see the progress
    if my_key not in my_dict.keys():
        my_dict[my_key]={}
        my_dict[my_key]['values']=[df.iloc[i]['another_column']]
    else:
        my_dict[my_key]['values'].append(df.iloc[i]['another_column'])
        
e=datetime.datetime.now()

print('operation took '+str(e-s)+' seconds')```