【问题标题】:Python numpy where function behaviorPython numpy where 函数行为
【发布时间】:2017-04-05 00:47:13
【问题描述】:

对使用 numpy 的 where 条件有疑问。我可以将 where 条件与 == 运算符一起使用,但不能将 where 条件与“是另一个字符串的一个字符串子字符串吗?”一起使用。

代码:

    import pandas as pd
    import datetime as dt
    import numpy as np

    data = {'name': ['Smith, Jason', 'Bush, Molly', 'Smith, Tina',    
        'Clinton,     Jake', 'Hamilton, Amy'],
        'age': [42, 52, 36, 24, 73],
        'preTestScore': [4, 24, 31, 2, 3],
        'postTestScore': [25, 94, 57, 62, 70]}
    df = pd.DataFrame(data, columns = ['name', 'age', 'preTestScore',     
    'postTestScore'])
    print "BEFORE---- "
    print df
    print "AFTER----- "
    df["Smith Family"]=np.where("Smith" in df['name'],'Y','N' )
    print df

输出:

    BEFORE-----

                name  age  preTestScore  postTestScore
    0   Smith, Jason   42             4             25
    1    Bush, Molly   52            24             94
    2    Smith, Tina   36            31             57
    3  Clinton, Jake   24             2             62
    4  Hamilton, Amy   73             3             70


    AFTER----- 
                name  age  preTestScore  postTestScore Smith Family
    0   Smith, Jason   42             4             25            N
    1    Bush, Molly   52            24             94            N
    2    Smith, Tina   36            31             57            N
    3  Clinton, Jake   24             2             62            N
    4  Hamilton, Amy   73             3             70            N

为什么 numpy.where 条件在上述情况下不起作用。 曾期望史密斯家族有价值观 是 ñ 是 ñ 否

但是没有得到那个输出。上面看到的输出都是 N,N,N,N,N 而不是在 df['name'] 中使用条件 "Smith" (也尝试过 str(df['name']).find("Smith") >-1 ),但这也不起作用。

知道哪里出了问题或者我可以做些什么不同的事情吗?

【问题讨论】:

    标签: python pandas numpy substring conditional-statements


    【解决方案1】:

    我认为你需要str.contains 来作为布尔掩码:

    print (df['name'].str.contains("Smith"))
    0     True
    1    False
    2     True
    3    False
    4    False
    Name: name, dtype: bool
    
    df["Smith Family"]=np.where(df['name'].str.contains("Smith"),'Y','N' )
    print (df)
                    name  age  preTestScore  postTestScore Smith Family
    0       Smith, Jason   42             4             25            Y
    1        Bush, Molly   52            24             94            N
    2        Smith, Tina   36            31             57            Y
    3  Clinton,     Jake   24             2             62            N
    4      Hamilton, Amy   73             3             70            N
    

    str.startswith:

    df["Smith Family"]=np.where(df['name'].str.startswith("Smith"),'Y','N' )
    print (df)
                    name  age  preTestScore  postTestScore Smith Family
    0       Smith, Jason   42             4             25            Y
    1        Bush, Molly   52            24             94            N
    2        Smith, Tina   36            31             57            Y
    3  Clinton,     Jake   24             2             62            N
    4      Hamilton, Amy   73             3             70            N
    

    如果想使用in 处理标量需要apply

    此解决方案更快,但如果 NaN 在列 name 中则不起作用。

    df["Smith Family"]=np.where(df['name'].apply(lambda x: "Smith" in x),'Y','N' )
    print (df)
                    name  age  preTestScore  postTestScore Smith Family
    0       Smith, Jason   42             4             25            Y
    1        Bush, Molly   52            24             94            N
    2        Smith, Tina   36            31             57            Y
    3  Clinton,     Jake   24             2             62            N
    4      Hamilton, Amy   73             3             70            N
    

    【讨论】:

    • 是的,耶斯瑞尔。您的回答确实有效,而且很有帮助。
    • 你能告诉我为什么 np.where() 可以与 == 一起使用,但不能与 str 函数中的字符串 find 或 substr 一起使用。
    • 我认为主要原因是如果使用findsubstr 它仅适用于标量,但在熊猫中使用数组。所以需要像 str.findstr.startswith 这样的 pandas 文本功能 - 请参阅 docs。美好的一天!你可以接受我的解决方案。谢谢。
    【解决方案2】:

    np.where("Smith" in df['name'],'Y','N' ) 的行为取决于df['name'] 产生的内容 - 我假设某种 numpy 数组。剩下的就是numpy

    In [733]: x=np.array(['one','two','three'])
    In [734]: 'th' in x
    Out[734]: False
    In [744]: 'two' in np.array(['one','two','three'])
    Out[744]: True
    

    in 是一个完整的字符串测试,适用于列表和字符串数组。这不是子字符串测试。

    np.char 有一堆函数将字符串函数应用于数组元素。这些大致相当于np.array([x.fn() for x in arr])

    In [754]: x=np.array(['one','two','three'])
    In [755]: np.char.startswith(x,'t')
    Out[755]: array([False,  True,  True], dtype=bool)
    In [756]: np.where(np.char.startswith(x,'t'),'Y','N')
    Out[756]: 
    array(['N', 'Y', 'Y'], 
          dtype='<U1')
    

    或者find

    In [760]: np.char.find(x,'wo')
    Out[760]: array([-1,  1, -1])
    

    pandas.str 方法似乎做了类似的事情;将字符串方法应用于数据系列的元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-26
      • 1970-01-01
      • 2019-09-30
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多