我有一个解析名字的数据框:
**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 = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ 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
有没有办法更快地完成这项工作?
答案 0 :(得分: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())
答案 1 :(得分:0)
另一种解决方案,利用熊猫的串功能&#39;系列:
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
可以接受与