You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取Pandas列的唯一值及其计数并转为带索引的DataFrame

解决Pandas提取唯一值计数并转为DataFrame的问题

嘿,作为Pandas新手碰到这个问题太正常啦!你已经迈出了正确的第一步——用df1['Genre'].value_counts()获取到了唯一值的计数Series,接下来转成DataFrame其实有几种简单的方法,我给你一一说明:

方法1:直接转为带索引的DataFrame(保留唯一值为索引)

如果你希望把Genre的唯一值继续作为DataFrame的索引,直接调用Series的to_frame()方法就可以了:

df_counts = df1['Genre'].value_counts().to_frame()

这样得到的DataFrame里,索引是Genre的各个唯一值,列名默认是原列名(也就是Genre),对应的值就是该类别出现的次数。

方法2:把唯一值转为普通列(生成整数索引)

如果你想把Genre的唯一值作为DataFrame的一列,同时用默认的整数索引,那就用reset_index()方法,还可以顺便给计数列起个更清晰的名字:

df_counts = df1['Genre'].value_counts().reset_index(name='Count')

执行后你会得到一个结构更直观的DataFrame:Genre列存唯一值,Count列存对应的出现次数,索引是从0开始的整数。

举个实际的例子帮你理解:
假设你的df1['Genre']列数据是:Action, Comedy, Action, Drama, Comedy, Comedy

  • 用value_counts()得到的Series是:
    Comedy    3
    Action    2
    Drama     1
    Name: Genre, dtype: int64
    
  • 用to_frame()得到的DataFrame:
    Genre
    Comedy3
    Action2
    Drama1
  • 用reset_index(name='Count')得到的DataFrame:
    GenreCount
    0Comedy3
    1Action2
    2Drama1

你可以根据自己的需求选其中一种方法,是不是很简单😉

内容的提问来源于stack exchange,提问作者maheswaran j

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:04:49