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

如何按Pandas DataFrame邮箱列的域名及@前缀子串排序

实现邮箱域名+前缀的排序方案

没问题,这需求很常见,咱们用Pandas就能轻松搞定!下面两种方法都能得到你预期的排序结果:

方法一:直观拆分法(适合新手理解)

先把邮箱拆分成前缀和域名两个临时列,明确按这两个维度排序,之后再删掉临时列:

import pandas as pd

# 构造你的原始DataFrame
data = {
    'name': ['Carl', 'Bob', 'Alice', 'David', 'Eve'],
    'email': ['carl@yahoo.com', 'bob@gmail.com', 'alice@yahoo.com', 'dave@hotmail.com', 'eve@gmail.com']
}
df = pd.DataFrame(data)

# 拆分邮箱为前缀(@前的字符串)和域名(@后的字符串)
df[['prefix', 'domain']] = df['email'].str.split('@', expand=True)

# 先按域名升序排序,再按前缀升序排序,最后重置索引
df_sorted = df.sort_values(by=['domain', 'prefix'], ascending=True).drop(columns=['prefix', 'domain']).reset_index(drop=True)

print(df_sorted)

方法二:简洁Key函数法(少写代码更高效)

不需要额外列,直接通过sort_values的key参数,从邮箱字符串中提取排序依据:

import pandas as pd

data = {
    'name': ['Carl', 'Bob', 'Alice', 'David', 'Eve'],
    'email': ['carl@yahoo.com', 'bob@gmail.com', 'alice@yahoo.com', 'dave@hotmail.com', 'eve@gmail.com']
}
df = pd.DataFrame(data)

# 用lambda函数生成排序key:先取域名,再取前缀
df_sorted = df.sort_values(
    by='email',
    key=lambda x: (x.str.split('@').str[1], x.str.split('@').str[0]),
    ascending=True
).reset_index(drop=True)

print(df_sorted)

最终输出结果

两种方法都会得到你想要的排序结果:

name             email
0    Bob    bob@gmail.com
1    Eve     eve@gmail.com
2  David  dave@hotmail.com
3  Alice  alice@yahoo.com
4   Carl   carl@yahoo.com

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:08:57