如何从具有多个值的dataframe列中删除重复项?

2024-05-14 15:36:47 发布

您现在位置:Python中文网/ 问答频道 /正文

数据:

The data

我想在不删除行的情况下删除“Borough”中的重复项,每个行只需要一个值

g2 = dfff.groupby(['Postcode'])["Borough"].agg( ','.join)
g3 = dfff.groupby(['Postcode'])["Neighbourhood"].agg( ','.join)
df2=pd.DataFrame(g2)
df3=pd.DataFrame(g3)
df4 = pd.merge(df2, df3, on='Postcode')

Tags: 数据dataframe情况aggpdpostcodedf2join
1条回答
网友
1楼 · 发布于 2024-05-14 15:36:47

试试这个:

# setup
df = pd.DataFrame({
    "data": ['scarborough, scarborough, scarborough', 'london,london', 'north york, north york', 'test,test']
})

# logic
def custom_dedup(s):
    return [*set([_.strip() for _ in s.split(',')])][0]

df['data'].apply(custom_dedup)

工作原理

  1. split():在逗号上拆分字符串,这将生成一个列表
  2. strip():从列表中的每个字符串中删除外部空格
  3. set():从该列表中获取唯一元素
  4. ...[0]:我们假设每个集合只有一个元素,所以取第一个元素

输入:

    data
0   scarborough, scarborough, scarborough
1   london,london
2   north york, north york
3   test,test

输出:

0    scarborough
1         london
2     north york
3           test

相关问题 更多 >

    热门问题