如果满足某个条件,如何在熊猫中增加列?

时间:2021-05-13 04:35:04

标签: python pandas string dataframe

我有一个数据框,例如:

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

1 个答案:

答案 0 :(得分:3)

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