【问题标题】:How to split a dataframe column based on a character and retain that character?如何根据字符拆分数据框列并保留该字符?
【发布时间】:2019-08-01 15:54:28
【问题描述】:

我无法弄清楚如何根据字符拆分数据框列并保留该字符串。以下是一些示例数据:

df = pd.DataFrame(
    {"sexage" : ['m45', 'f43']}
)

我想要的是一个单独的列,其中包含男性/女性字母和一个单独的列,其中包含年龄。

当我执行df['sexage'].str.split('m|f', expand=True) 时,第一列中没有任何值。但是当我执行df['sexage'].str.split('(m|f)', expand=True) 时,我会得到一个我不想要的额外空白列。

我知道我可以使用 df['sexage'].str[0]df['sexage'].str[1:] 按位置选择它们,但我想知道是否可以使用正则表达式来代替。

【问题讨论】:

  • df['sexage'].str.split('(?<=[mf])(?=\d)', expand=True) - 它适用于 Python 3.7+。否则,请尝试df['sexage'].str.extract(r'([mf])(\d+)', expand=True)
  • df.sexage.str.extract('(?P<sexe>\D+)(?P<age>\d+)')

标签: python regex pandas character


【解决方案1】:

试试extract

df.sexage.str.extract('(\D+)(\d+)')

输出:

    0   1
0   m   45
1   f   43

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    相关资源
    最近更新 更多