【问题标题】:How to implement where clause in python如何在python中实现where子句
【发布时间】: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


    【解决方案1】:

    不需要新列:

    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
    

    【讨论】:

    • 感谢你们,这确实是一个更好的方法。但是,如果我在 where 子句中有多个条件,这会起作用吗?就像我尝试了以下但得到错误:TypeError: cannot compare a dtyped [int64] array with a scalar of type [bool] Code: newdata4 = df[df['Address'].str[0] == 'N' & df ['年龄'] > 30]
    • @singularity2047 - 你很依赖,只需要(),就像newdata4 = df[(df['Address'].str[0] == 'N') & (df['Age'] > 30)] 一样
    猜你喜欢
    • 2017-01-30
    • 2020-01-28
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 2011-03-29
    相关资源
    最近更新 更多