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

如何合并DataFrame单列中相同取值的对象并保留唯一值?

如何提取DataFrame中Genre列的唯一值?

嗨,这个需求其实在Pandas里有好几种简单直接的实现方式,我给你拆解一下:

方法1:用unique()获取唯一值数组

这是最直接的方式,会返回一个包含所有唯一值的NumPy数组,代码示例如下:

import pandas as pd

# 先构造你提供的DataFrame
df = pd.DataFrame({
    'Genre': ['Horror', 'Horror', 'Romance', 'Fiction', 'Romance']
})

# 获取Genre列的唯一值
unique_genres = df['Genre'].unique()
print(unique_genres)
# 输出结果: ['Horror' 'Romance' 'Fiction']

如果需要把结果转回DataFrame格式(保持原列名结构),只需要再包装一下:

unique_df = pd.DataFrame({'Genre': unique_genres})
print(unique_df)

方法2:用drop_duplicates()生成去重后的DataFrame

如果你想直接得到一个去掉重复行的新DataFrame(保留每个类别第一次出现的行),可以用这个方法:

# 对Genre列去重,返回新的DataFrame
unique_df = df.drop_duplicates(subset='Genre')
print(unique_df)

要是觉得去重后的索引不连续,可以加上reset_index(drop=True)重置索引:

unique_df = df.drop_duplicates(subset='Genre').reset_index(drop=True)

额外小技巧:统计每个类别的出现次数

如果你不仅需要唯一值,还想知道每个Genre出现了多少次,可以用value_counts():

genre_count = df['Genre'].value_counts()
print(genre_count)

输出会包含每个类别的计数,索引就是对应的唯一Genre值。

这几个方法都能完美满足你的需求,根据自己的实际场景选择就行~

内容的提问来源于stack exchange,提问作者Thom JAckson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:17:35