如何基于熊猫数据框中的行值的某些部分进行过滤

时间:2019-02-20 20:28:29

标签: python pandas dataframe filter

我有一个熊猫数据框,如下所示:

Name

现在,我想将新列中的某些值分配给包含一些子字符串的text列。例如,如果它包含星期一,那么我们将as分配给他们,如果它包含city,我们将 +------+---+----+ |Name |age|new | +------+---+----+ |Mona |12 |text| +------+---+----+ |Monika|25 |text| +------+---+----+ |Tomas |3 |city| +------+---+----| |Ilyas |47 |city| +------+---+----+ 分配给他们。

所以输出必须是:

df['new'] = np.nan    
df['new'] = df['new'].mask( 'Mon' in df['Name'], 'text')    
df['new'] = df['new'].mask( 'as' in df['Name'], 'city')

我写了以下代码,但没有用:

class AnimalPlanet {

  "lions" should "return the name of the lion" in {
    println(lion.name)
  }
}

4 个答案:

答案 0 :(得分:1)

如果您的逻辑变得复杂,则可能需要将映射封装到一个函数中:

def map_func(name):
    if 'Mon' in name:
        return 'text'
    elif 'as' in name:
        return 'city'

df['Name'].map(map_func)

结果:

0    text
1    text
2    city
3    city
Name: Name, dtype: object

答案 1 :(得分:0)

这应该做:

df['new']=np.where(df.Name.str.contains('Mon'), 'text', 'city')

np.where的工作方式类似于Excel的IF:如果满足条件,则用'text'填充,否则用'city'填充。

答案 2 :(得分:0)

Df.loc[df.name.str.endswith('as'), 'new'] = 'city'
Df.loc[df.name.str.startswith('Mon'), 'new'] = 'text'

Str有一种用于此类问题的方法startsWith和endsWith。 也许可以单行完成,但是现在我什么都没想到。

Loc始终有助于选择和更新条件数据。

编辑:Juan C是正确的,应该是“包含”而不是“ startsWith”,我不好。

答案 3 :(得分:0)

我认为这是最好的选择,因为它将处理不区分大小写的匹配并在不满足任何条件的情况下填充NaN

import numpy as np

     Name  Age
0    Mona   12
1  Monika   25
2   Tomas    3
3   Ilyas   47

default = np.where(df.Name.str.contains('as', case=False), 'city', np.nan)
cond = np.where(df.Name.str.contains('Mon', case=False), 'text', default)

df.assign(new=cond)

     Name  Age   new
0    Mona   12  text
1  Monika   25  text
2   Tomas    3  city
3   Ilyas   47  city
相关问题