我有pandas dataframe'lc',只想将整数值替换为字符串。

            indexsum
    82445    start
    82446    start
    82447    start
    82448       11
    82449       10
    82450       12
    82451       12
    82452        9
    82453       11
    82454        9
    82455       10
    82456       10
    82457        9
    82458        9
    82459        9


我已经使用了pd.cut方法并编写了这样的代码,但是出现了错误消息。如果我在同一列中有字符串和整数值,似乎无法使用此代码。我必须使用什么功能? (而不是映射方法)

 lc['lcindex'] = pd.cut(lc.indexsum, bins=[0,4,8,12,16], labels=["growth","mature","revival","decline"])

 TypeError: unorderable types: str() > float()

最佳答案

让我们将pd.to_numericerrors='coerece'一起使用:

df['lc'] = pd.cut(pd.to_numeric(df.indexsum, errors='coerce'),bins=[-np.inf,0,4,8,12,16], labels=["start","growth","mature","revival","decline"]).fillna('start')


输出:

      indexsum       lc
82445    start    start
82446    start    start
82447    start    start
82448       11  revival
82449       10  revival
82450       12  revival
82451       12  revival
82452        9  revival
82453       11  revival
82454        9  revival
82455       10  revival
82456       10  revival
82457        9  revival
82458        9  revival
82459        9  revival

09-30 13:50