在pandas数据框中识别含标点的行
我有一个包含名字的数据表,这些名字已经被处理过:
**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
我想要更新,如果一个名字包含标点符号、数字或者空格,就把BAD标记为1。
**FIRST_NAME** **BAD**
Jon 0
Colleen 0
William 0
Todd 0
J-Crew 1
&Re Inc 1
123Trust 1
这是我的代码:
punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ 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 个回答
1
还有一种解决方案,利用了pandas的Series字符串处理功能:
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("""[!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ 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("""[!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~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
可以接受一个正则表达式模式来进行匹配。
4
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())