如何在 python 中实现 where 子句

How to implement where clause in python

我想使用 Python 复制 SQL 中 where 子句的作用。很多时候 where 子句中的条件可能很复杂并且有多个条件。我可以通过以下方式做到这一点。但我认为应该有更聪明的方法来实现这一目标。我有以下数据和代码。

我的要求是:我想 select 所有列只有当地址中的第一个字母是 'N' 时。这是初始数据框。

d = {'name': ['john', 'tom', 'bob', 'rock', 'dick'], 'Age': [23, 32, 45, 42, 28], 'YrsOfEducation': [10, 15, 8, 12, 10], 'Address': ['NY', 'NJ', 'PA', 'NY', 'CA']}
import pandas as pd
df = pd.DataFrame(data = d)
df['col1'] = df['Address'].str[0:1] #creating a new column which will have only the first letter from address column
n = df['col1'] == 'N' #creating a filtering criteria where the letter will be equal to N
newdata = df[n] # filtering the dataframe 
newdata1 = newdata.drop('col1', axis = 1) # finally dropping the extra column 'col1'

所以在 7 行代码之后我得到了这个输出:

我的问题是我怎样才能更有效地做到这一点,或者有没有更聪明的方法来做到这一点?

不需要新列:

newdata = df[df['Address'].str[0] == 'N'] # filtering the dataframe 
print (newdata)
  Address  Age  YrsOfEducation  name
0      NY   23              10  john
1      NJ   32              15   tom
3      NY   42              12  rock