简体   繁体   中英

Using pd.Series.value_counts in Python. Using numpy.where, numpy.unique to replace array

I have this code:-

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

Now, I want to write a code to create a new array in which +1 replaces 9 in every occurrence and All other entries (ie, the digits 0 through 8 ) should be replaced by −1. Also, create a Pandas Series (with a sorted index) that records the counts of each class Pandas Series with the integers −1− and +1 on the index (sorted in increasing order) and the corresponding counts as the data. I want to use these functions to solve it using numpy.where , numpy.unique and pandas.Series.value_counts .

You can use np.where first:

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

Or you can count in np.unique :

a, b = np.unique(new, return_counts=True)

s = pd.Series(b, index=a)
print (s)
-1    26
 1     3
dtype: int64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM