代码之家  ›  专栏  ›  技术社区  ›  davy

对列数据帧中的值进行排序和计数(Python)

  •  0
  • davy  · 技术社区  · 2 年前

    我有下一个数据帧

    测向

    enter image description here

    我这样计算数值

    enter image description here

    我希望类别值按下一个顺序排列:

    1 1.

    4 1.

    7 2.

    10 1.

    等等

    以上升的方式与他们的价值观有关

    3 回复  |  直到 2 年前
        1
  •  0
  •   Yefet    2 年前

    您可以使用 sort_index()

    df['col_1'].value_counts().sort_index()
    
        2
  •  0
  •   mitoRibo    2 年前

    您可以在调用value_counts后对索引进行排序。这里有一个例子

    df = pd.DataFrame({'x':[1,2,2,2,1,4,5,5,4,3,5,6,3]})
    df['x'].value_counts().sort_index()
    

    输出:

    1    2
    2    3
    3    2
    4    2
    5    3
    6    1
    Name: x, dtype: int64
    
        3
  •  0
  •   Pramendra Pandey    2 年前

    enter image description here

    然后通过下面的代码对其进行排序,下面是输出

    df1.groupby(by=['Cat']).count().sort_values(by='col1')
    

    enter image description here