【发布时间】:2018-10-27 09:42:44
【问题描述】:
我正在尝试按列获取唯一计数,但我的数组具有分类变量(dtype 对象)
val, count = np.unique(x, axis=1, return_counts=True)
虽然我收到这样的错误:
TypeError: The axis argument to unique is not supported for dtype object
我该如何解决这个问题?
样本 x:
array([[' Private', ' HS-grad', ' Divorced'],
[' Private', ' 11th', ' Married-civ-spouse'],
[' Private', ' Bachelors', ' Married-civ-spouse'],
[' Private', ' Masters', ' Married-civ-spouse'],
[' Private', ' 9th', ' Married-spouse-absent'],
[' Self-emp-not-inc', ' HS-grad', ' Married-civ-spouse'],
[' Private', ' Masters', ' Never-married'],
[' Private', ' Bachelors', ' Married-civ-spouse'],
[' Private', ' Some-college', ' Married-civ-spouse']], dtype=object)
需要以下计数:
for x_T in x.T:
val, count = np.unique(x_T, return_counts=True)
print (val,count)
[' Private' ' Self-emp-not-inc'] [8 1]
[' 11th' ' 9th' ' Bachelors' ' HS-grad' ' Masters' ' Some-college'] [1 1 2 2 2 1]
[' Divorced' ' Married-civ-spouse' ' Married-spouse-absent'
' Never-married'] [1 6 1 1]
【问题讨论】:
-
无论该错误如何,该数组中都没有第二个轴。是一维的
-
当您想要的只是每个字符串的计数时,为什么要使用
axis?使用axis是您想要唯一的行或列。x.T迭代有什么问题?
标签: python python-3.x numpy unique frequency