本人小白,高手进来帮我解释下这是为什么 | python | python 技术论坛-江南app体育官方入口

ser = pd.series([1, 2, 1, 3, 5, 6, 1, 6, 6])
print(ser)
def func(s):
n = s.index[0]
df_choice = ser[:n 1][ser[:n 1] == ser[:n 1][-1:].values[0]]
if len(df_choice)>1:
m = df_choice.tail(2).index[1]-df_choice.tail(2).index[0]
else:
m=’不显示’
return m
print(ser.rolling(1).apply(func))

为什么当自定义函数的else的m值为字符时会有出错信息:typeerror: must be real number, not str
当我把m=’不显示’改成m=123 时就运行成功了

讨论数量: 4
import numpy as np
import pandas as pd
ser = pd.series([1, 2, 1, 3, 5, 6, 1, 6, 6])
def func(s):
    n = s.index[0]
    df_choice = ser[:n  1][ser[:n  1] == ser[:n  1][-1:].values[0]]
    if len(df_choice) > 1:
        m = df_choice.tail(2).index[1] - df_choice.tail(2).index[0]
    else:
        # np.nan 是浮点类型
        m = np.nan
    return m
print(ser.rolling(1).apply(func))
# 不显示nan的行
print(ser.rolling(1).apply(func).dropna())
# rolling.apply()中的func只能返回浮点数,https://github.com/pandas-dev/pandas/issues/48652
1年前
(楼主) 1年前
  • 你都验证出问题所在了,大胆点,直接得出结论,返回类型不一致,所以报错.
  • 报错是这个语言的语法机制, 需要返回类型一致. 要么返回值全是数字,要么全是其它.
  • 建议优先了解基础语法.
1年前
(楼主) 1年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
网站地图