在熊猫列中的字符之间插入连字符

Insert hyphen between chracters in a panda column

考虑以下数据框

pd.DataFrame.from_dict({'col_1': ["abcdefg", "hellowworld", "Whosebug", "thankyou"]})

我想在每 4 个字符后添加一个连字符

期望的输出是

pd.DataFrame.from_dict(data = {'col_1': ["abcd-efg", "hell-owwo-rld", "stac-kove-rflo-w", "than-kyou"]})

用添加的 -

替换之前的每个组
df['col_2'] =df['col_1'].str.replace(r'(\w{4})',r'-',regex=True).str.strip('\-')

        col_2
0        abcd-efg
1    hell-owworld
2  stac-koverflow
3       than-kyou

或者你想要

df['col_2'] =df['col_1'].str.replace(r'(\w{4})',r'-',regex=True).str.strip('\-')

        col_1             col_2
0        abcdefg          abcd-efg
1    hellowworld     hell-owwo-rld
2  Whosebug  stac-kove-rflo-w
3       thankyou        than-kyou

您可以在此处使用 str.replace

df["col_1"] = df["col_1"].str.replace(r'(?<=^.{4})', r'-')