【问题标题】:Using pd.Series.value_counts in Python. Using numpy.where, numpy.unique to replace array在 Python 中使用 pd.Series.value_counts。使用 numpy.where、numpy.unique 替换数组
【发布时间】:2021-03-03 05:29:37
【问题描述】:

我有这个代码:-

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 Series(带有排序索引),记录每个类 Pandas Series 的计数,索引上的整数为 -1− 和 +1(按升序排序),并将相应的计数作为数据。我想通过numpy.wherenumpy.uniquepandas.Series.value_counts使用这些函数来解决它。

【问题讨论】:

    标签: python arrays pandas numpy


    【解决方案1】:

    你可以先使用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
    

    【讨论】:

    • 感谢您的帮助。我有一个额外的问题。如何添加分类为 -1−1 和 +1+1 的 Pandas DataFrame 作为索引,并包含两列:train 和 test。那么,每一行的条目分别是训练目标 y_digits_train 和测试目标 y_digits_test 中每个类别的出现次数。
    • @n53 - 不确定是否理解,您能否通过编辑从问题数据中创建预期输出?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 2017-09-23
    • 2017-08-27
    • 2012-09-02
    相关资源
    最近更新 更多