![](/img/trans.png)
[英]How to replace values of an array using numpy array and numpy.where
[英]Using pd.Series.value_counts in Python. Using numpy.where, numpy.unique to replace array
我有这个代码: -
y = digits.target
print(y[31:60])
with output [9 5 5 6 5 0 9 8 9 8 4 1 7 7 3 5 1 0 0 2 2 7 8 2 0 1 2 6 3]
y = digits.target
ans_2 = pd.Series.value_counts(y)
ans = ans_2.sort_index()
with output
0 178
1 182
2 177
3 183
4 181
5 182
6 181
7 179
8 174
9 180
现在,我想编写一个代码来创建一个新array
,其中 +1 替换每次出现的 9 并且所有其他条目(即数字 0 到 8 )应替换为 -1。 此外,创建一个 Pandas 系列(带有排序索引),记录每个 class Pandas 系列的计数,索引上的整数为 -1− 和 +1,数据按递增顺序排序。 我想使用这些函数使用numpy.where
、 numpy.unique
和pandas.Series.value_counts
来解决它。
您可以先使用np.where
:
y = digits.target
new = np.where(y == 9, 1, -1)
s = pd.Series.value_counts(new).sort_index()
print (s)
-1 26
1 3
dtype: int64
或者您可以计算np.unique
:
a, b = np.unique(new, return_counts=True)
s = pd.Series(b, index=a)
print (s)
-1 26
1 3
dtype: int64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.