首页 > 解决方案 > 如果满足某个条件,如何增加熊猫的列?

问题描述

例如,我有一个数据框:

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

标签: pythonpandasstringdataframe

解决方案


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 次(第一种选择)
    • .+:匹配任何字符一次或多次(第二种选择)

online regex demo


推荐阅读