【问题标题】:Why does Python function return 1.0 (float) when `return 1` is specified?为什么指定 `return 1` 时 Python 函数会返回 1.0 (float)?
【发布时间】: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


【解决方案1】:

原因是np.nan 被认为是float。这使得系列类型为float。除非您希望列的类型为 Object [即任何事物]。这是低效且不可取的,我拒绝向您展示如何做到这一点。

如果您可以使用替代值来代替 np.nan,例如0,那么有一个解决方法。您可以将NaN 值替换为0,然后转换为int

s = pd.Series([1, np.nan, 2, 3])

print(s)
# 0    1.0
# 1    NaN
# 2    2.0
# 3    3.0
# dtype: float64

s = s.fillna(0).astype(int)

print(s)
# 0    1
# 1    0
# 2    2
# 3    3
# dtype: int32

【讨论】:

  • 非常感谢您的解释和解决方案。它有效!
【解决方案2】:

使用astype(int)

例如:

df['Single'] = e.apply(Single).astype(int)

【讨论】:

    猜你喜欢
    • 2019-08-25
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多