Given a DataFrame:
name email
0 Carl [email protected]
1 Bob [email protected]
2 Alice [email protected]
3 David [email protected]
4 Eve [email protected]
How can it be sorted according to the email's domain name (alphabetically, ascending), and then, within each domain group, according to the string before the "@"?
The result of sorting the above should then be:
name email
0 Bob [email protected]
1 Eve [email protected]
2 David [email protected]
3 Alice [email protected]
4 Carl [email protected]
Use:
df = df.reset_index(drop=True)
idx = df['email'].str.split('@', expand=True).sort_values([1,0]).index
df = df.reindex(idx).reset_index(drop=True)
print (df)
name email
0 Bob [email protected]
1 Eve [email protected]
2 David [email protected]
3 Alice [email protected]
4 Carl [email protected]
Explanation:
reset_index
with drop=True
for unique default indicessplit
values to new DataFrame
and sort_values
reindex
to new orderIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With