使用层次结构条件SQL Python Pandas删除重复项

发布于 2025-02-06 09:30:53 字数 711 浏览 3 评论 0原文

我需要在大型数据库中删除重复项,但是要删除的行必须基于使用sqlite或python pandas的层次结构。是否有一种有效的方法可以解决此问题?最好使用Python Pandas DataFrame,但SQLite也可以。

ID文本类别
1文本优先级3
2文本优先级1
3文本优先2
4文本2优先级3
5文本2优先级

应转换为:

ID文本类别
2文本优先级1
5文本2优先级2优先级2

I need to delete duplicates in a large database, but the rows to be deleted must be based on a hierarchy using either SQLite or Python Pandas. Is there a efficient way to relize this? preferably using python pandas dataframe but SQLite is also fine.

IDTextCategory
1textPriority 3
2textPriority 1
3textPriority 2
4text 2Priority 3
5text 2Priority 2

should turn to this:

IDTextCategory
2textPriority 1
5text 2Priority 2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

谈场末日恋爱 2025-02-13 09:30:53

尝试以下尝试:

df = df.sort_values(by=['Text','Category'], ascending=[True,True])
df.groupby('Text')['Category'].first().reset_index()

输出:

索引文本类别
0文本优先级1
1文本2优先级2

Try this:

df = df.sort_values(by=['Text','Category'], ascending=[True,True])
df.groupby('Text')['Category'].first().reset_index()

Output:

indexTextCategory
0textPriority 1
1text 2Priority 2
只怪假的太真实 2025-02-13 09:30:53

@drakax非常相似的方法,但使用drop_duplicates而不是groupby首先

import pandas as pd

df = pd.DataFrame({
    'ID': [1, 2, 3, 4, 5],
    'Text': ['text', 'text', 'text', 'text 2', 'text 2'],
    'Category': ['Priority 3', 'Priority 1', 'Priority 2', 'Priority 3', 'Priority 2'],
})

df.sort_values(['Text','Category']).drop_duplicates('Text')

Very similar approach to @Drakax but using drop_duplicates instead of groupby and first

import pandas as pd

df = pd.DataFrame({
    'ID': [1, 2, 3, 4, 5],
    'Text': ['text', 'text', 'text', 'text 2', 'text 2'],
    'Category': ['Priority 3', 'Priority 1', 'Priority 2', 'Priority 3', 'Priority 2'],
})

df.sort_values(['Text','Category']).drop_duplicates('Text')
能否归途做我良人 2025-02-13 09:30:53

避免在可能的时候进行分类,请使用分类来定义优先级的顺序,并获取每组最小的索引:

# priorities in order
priorities = ['Priority 1', 'Priority 2', 'Priority 3']
# set up Categorical
df['Category'] = pd.Categorical(df['Category'], priorities, ordered=True)
# min per group 
df.loc[df.groupby('Text')['Category'].idxmin()]

输出:

   ID    Text    Category
1   2    text  Priority 1
4   5  text 2  Priority 2

Avoid sorting when you can, use a Categorical to define the order of the priorities and get the index of the min per group:

# priorities in order
priorities = ['Priority 1', 'Priority 2', 'Priority 3']
# set up Categorical
df['Category'] = pd.Categorical(df['Category'], priorities, ordered=True)
# min per group 
df.loc[df.groupby('Text')['Category'].idxmin()]

Output:

   ID    Text    Category
1   2    text  Priority 1
4   5  text 2  Priority 2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文