【发布时间】:2018-05-08 11:29:31
【问题描述】:
我有很多字符串,其中一些由 1 个句子组成,有些由多个句子组成。我的目标是确定哪些单句字符串以感叹号“!”结尾。
我的代码给出了一个奇怪的结果。如果找到,它不会返回“1”,而是返回 1.0。我试过:return int(1) 但这没有帮助。我对编码还很陌生,不明白,为什么会这样以及如何将 1 作为整数?
'Sentences'
0 [This is a string., And a great one!]
1 [It's a wonderful sentence!]
2 [This is yet another string!]
3 [Strange strings have been written.]
4 etc. etc.
e = df['Sentences']
def Single(s):
if len(s) == 1: # Select the items with only one sentence
count = 0
for k in s: # loop over every sentence
if (k[-1]=='!'): # check if sentence ends with '!'
count = count+1
if count == 1:
return 1
else:
return ''
df['Single'] = e.apply(Single)
这会返回正确的结果,但应该是 '1' 而不是 '1.0'。
'Single'
0 NaN
1 1.0
2 1.0
3
4 etc. etc.
为什么会这样?
【问题讨论】:
-
您的函数正在返回
1- 但您实际上并没有查看返回值;您只会看到从数据框中检索到的值。我对 Pandas 不熟悉(我认为这是df的来源),但我猜它决定浮点数是表示数字和空字符串混合的最合适的数据类型。
标签: python python-3.x series