[英]Sort Pandas Dataframe by substrings of a column
Given a DataFrame: 给定一个DataFrame:
name email
0 Carl carl@yahoo.com
1 Bob bob@gmail.com
2 Alice alice@yahoo.com
3 David dave@hotmail.com
4 Eve eve@gmail.com
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 bob@gmail.com
1 Eve eve@gmail.com
2 David dave@hotmail.com
3 Alice alice@yahoo.com
4 Carl carl@yahoo.com
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 bob@gmail.com
1 Eve eve@gmail.com
2 David dave@hotmail.com
3 Alice alice@yahoo.com
4 Carl carl@yahoo.com
Explanation : 说明 :
reset_index
with drop=True
for unique default indices 对于唯一的默认索引,首先使用drop=True
reset_index
split
values to new DataFrame
and sort_values
然后split
值split
为新的DataFrame
和sort_values
reindex
to new order 最后reindex
新订单 Option 1 选项1
sorted
+ reindex
sorted
+ reindex
df = df.set_index('email')
df.reindex(sorted(df.index, key=lambda x: x.split('@')[::-1])).reset_index()
email name
0 bob@gmail.com Bob
1 eve@gmail.com Eve
2 dave@hotmail.com David
3 alice@yahoo.com Alice
4 carl@yahoo.com Carl
Option 2 选项2
sorted
+ pd.DataFrame
sorted
+ pd.DataFrame
As an alternative, you can ditch the reindex
call from Option 1 by re-creating a new DataFrame. 作为替代方案,您可以通过重新创建新的DataFrame来放弃来自选项1的reindex
调用。
pd.DataFrame(
sorted(df.values, key=lambda x: x[1].split('@')[::-1]),
columns=df.columns
)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.