python - 在数据框python的每一行中按字母顺序对单词进行排序
问题描述
我在数据框中有一列包含字符串值,如下所示:
sortdf=pd.DataFrame(data= {'col1':["hello are you","what happenend","hello you there","issue is in our program","whatt is your name"]})
我想按字母顺序对元素中的每个单词进行排序。
期望的输出:
col1
0 are hello you
1 happenend what
2 hello there you
3 is in issue our program
4 is name whatt your
我尝试使用以下代码执行此操作:
sortdf['col1']. sort()
但是这段代码不起作用。
解决方案
pd.Series.apply
与匿名lambda
函数一起使用:
sortdf['col1'] = sortdf['col1'].apply(lambda x: ' '.join(sorted(x.split())))
pd.Series.sort
是不合适的,因为 (a) 这对系列元素而不是系列元素中的单词进行排序,并且 (b) 该方法已被弃用,取而代之的是sort_values
.
这个想法是将一个字符串拆分为一个单词列表,按字母顺序排序,然后重新加入一个字符串。
结果:
col1
0 are hello you
1 happenend what
2 hello there you
3 in is issue our program
4 is name whatt your
或者,列表推导可能更有效:
sortdf['col1'] = [' '.join(sorted(x)) for x in sortdf['col1'].str.split()]
推荐阅读
- reactjs - 在本机反应中增加 AsyncStorage 大小限制
- php - mysql查询到数组
- ios - 我可以更改我的应用在默认 iOS 共享表中的位置吗?
- antlr4 - ANTLR:如何使用 ANTLR 4 根据索引位置解析固定长度的文本文件?
- python - 如何从fabric2组中获取正在处理的主机
- vue.js - 发出 Axios 请求时加载微调器
- javascript - 单击时保持元素突出显示
- javascript - 路由模块在 APP_INITIALIZER 之前加载
- mysql - 如何在 SQL 表中找到所有可能的组合?
- c# - 使用 async/await 时是否需要使字段线程安全?