2014-10-27 36 views
0

我有名字的数据帧被解析:在大熊猫的数据帧与标点符号标识行

**FIRST_NAME** 
    Jon 
    Colleen 
    William 
    Todd 
    J.- 
    &Re Inc 
    123Trust 

我创建一个列标志的名称,如果它是好还是坏:

df['BAD']=pd.Series(np.zeros(1),index = df.index) 

    **FIRST_NAME**  **BAD** 
    Jon      0 
    Colleen     0 
    William     0 
    Todd     0 
    J-Crew     0 
    &Re Inc     0 
    123Trust    0 

如果FIRST_NAME包含标点,数字或空格,我想更新BAD = 1。

**FIRST_NAME**  **BAD** 
    Jon      0 
    Colleen     0 
    William     0 
    Todd     0 
    J-Crew     1 
    &Re Inc     1 
    123Trust    1 

这里是我的代码:

punctuation = '!"#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~ 1234567890' 
    i=0 
    while i <int(len(dfcopy)): 
     for p in punctuation1: 
      if (df['Bad'][i]==1): 
       df['Bad'][i]=1 
      elif(p in list(df.iloc[i,1])and df['Bad'][i]==0): 
       df['Bad'][i]=1 
      else: 
       df['Bad'][i]=0 
     i=i+1 

有没有办法更快地做到这一点?

回答

2
df['Bad'] = df.First_Name.map(lambda v: any(char in v for char in punctuation)) 

另一种可能性:使您的标点符合punctuation = set(punctuation)。然后,你可以这样做:

df['Bad'] = df.First_Name.map(lambda v: bool(set(v) & punctuation)) 

此外,如果你真的只是想知道,如果字符串中的所有字符是字母,你可以这样做:

df['Bad'] = df.First_Name.map(lambda v: v.isalpha()) 
+0

谢谢!我用“set”来使用你的第二个解决方案。 – jgaw 2014-10-27 19:20:24

0

另一种解决方案,利用串功能大熊猫系列:

In [130]: temp 
Out[130]: 
     index     time complete 
row_0  2     test   0 
row_1  3 2014-10-23 14:00:00   0 
row_2  4 2014-10-26 08:00:00   0 
row_3  5 2014-10-26 10:00:00   0 
row_4  6 2014-10-26 11:00:00   0 

In [131]: temp.time.str.contains("""[!"#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~ 1234567890]""") 
Out[131]: 
row_0 False 
row_1  True 
row_2  True 
row_3  True 
row_4  True 
Name: time, dtype: bool 

In [135]: temp['is_bad'] = temp.time.str.contains("""[!"#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~1234567890]""").astype(int) 


In [136]: temp 
Out[136]: 
     index     time complete is_bad 
row_0  2     test   0  0 
row_1  3 2014-10-23 14:00:00   0  1 
row_2  4 2014-10-26 08:00:00   0  1 
row_3  5 2014-10-26 10:00:00   0  1 
row_4  6 2014-10-26 11:00:00   0  1 

pandas.Series.str.contains可以接受一个正则表达式模式来匹配