python - 如果满足某个条件,如何增加熊猫的列?
问题描述
例如,我有一个数据框:
ID Description
1 Long lasting glasses,Fire resistant,Polarizer
我希望每个描述列只包含 10 个字符的最大长度,如果超过了应该形成新列。例子:
ID Description Description2 Description3 Description4 Description5
1 Long Lasti ng glasses ,Fire resi stant,Pola rizer
解决方案
str.extractall
+unstack
我们可以extract
在正则表达式模式中捕获所有出现的组,然后unstack
重塑
df['Description'].str.extractall(r'(.{10}|.+$)')[0].unstack()
match 0 1 2 3 4
0 Long lasti ng glasses ,Fire resi stant,Pola rizer
正则表达式详细信息:
(.{10}|.+$)
: 第一个捕获组.{10}
: 匹配任何字符 10 次(第一种选择).+
:匹配任何字符一次或多次(第二种选择)
推荐阅读
- reactjs - 禁用特定路由器及其嵌套路由器的组件
- php - 在多维 JSON 数组中搜索值 (PHP)
- wordpress - 我应该如何自动为我的 Gulp CSS 文件添加前缀?
- vue.js - 如何使用全局变量模拟商店
- powershell - PowerShell for 来自文件的循环
- arrays - 有序 postgresql 数组中大于 x 的最小值的位置(优化)
- swiftui - SwiftUI:在列表中切换 JSON 属性
- r - 如果多列中的 NA 超过 25%,则删除行
- python - ImportError:无法导入名称“PasswordsChangeView”
- jms - ActiveMQ - 我可以用延迟的消息队列替换调度程序插件吗?