Python – 将单个值分类会产生错误“输入数组必须是一维的”

huangapple go评论70阅读模式
英文:

Python - Categorise a single value yields error "Input array must be 1 dimensional"

问题

我正在尝试对单个浮点数进行分类避免使用一系列的`if``elif`语句而是使用`pd.cut`。

为什么下面的两段代码会产生错误 `Input array must be 1 dimensional`?

    import pandas as pd
    import numpy as np
    pd.cut(0.96,bins=[0,0.5,1,10],labels=['A','B','C'])
    pd.cut(np.array(0.96),bins=[0,0.95,1,10],labels=['A','B','C'])
英文:

I am trying to categorise single float numbers avoiding a list of if and elif statements using pd.cut.

Why the 2 codes below yield error Input array must be 1 dimensional?

import pandas as pd
import numpy as np
pd.cut(0.96,bins=[0,0.5,1,10],labels=['A','B','C'])
pd.cut(np.array(0.96),bins=[0,0.95,1,10],labels=['A','B','C'])

答案1

得分: 1

pd.cut操作的对象是类似数组的对象(正如它在第一个参数的文档中所述:x : array-like)。当你尝试切割单个元素时,它是一个零维数组。如果你只是在np.array调用周围加上[],你会得到你想要的结果:

>>> pd.cut(np.array([0.96]),bins=[0,0.95,1,10],labels=['A','B','C'])
['B']
Categories (3, object): ['A' < 'B' < 'C']

当你执行np.array(0.96)时,它会返回一个包含该对象的零维数组,根据np.array的文档。你也可以使用ndmin参数来强制Numpy在调用时返回一个一维数组:np.array(0.96, ndmin=1) -> array([0.96])

英文:

pd.cut operates over an array-like object (as it states in the documentation for its first paramater: x : array-like). When you try to cut a single element, it's a 0-dimensional array. If you just say wrap [] around your np.array call, you'll get your desired result:

&gt;&gt;&gt; pd.cut(np.array([0.96]),bins=[0,0.95,1,10],labels=[&#39;A&#39;,&#39;B&#39;,&#39;C&#39;])
[&#39;B&#39;]
Categories (3, object): [&#39;A&#39; &lt; &#39;B&#39; &lt; &#39;C&#39;]

When you do np.array(0.96), it will return a 0-dimensional array containing that object, per the documentation for np.array. You could also use the ndmin parameter to force Numpy to return a 1-dimensional array on your call: np.array(0.96, ndmin=1) -&gt; array([0.96]).

huangapple
  • 本文由 发表于 2023年2月13日 23:12:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75437730.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定