【发布时间】:2018-09-17 12:58:10
【问题描述】:
我想使用 Python 复制 where 子句在 SQL 中的作用。很多时候,where 子句中的条件可能很复杂并且有多个条件。我可以通过以下方式做到这一点。但我认为应该有一个更聪明的方法来实现这一点。我有以下数据和代码。
我的要求是:我只想在地址中的第一个字母为“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 行代码之后,我得到了这个输出:
我的问题是我怎样才能更有效地做到这一点,或者有什么更聪明的方法可以做到这一点?
【问题讨论】:
标签: sql python-3.x pandas where-clause