熊猫str.extract和concat列

时间:2020-04-20 15:00:10

标签: python pandas extract

实际上,我想提取数据框str列的信息,并将此信息作为新列附加到管道中。

当前我正在做

(
    pd.DataFrame({'raw': ['name_20200304', 'other_20200305']})
    .pipe(lambda df: pd.concat([df, df.raw.str.extract(r"(?P<name>\w+)_(?P<date>\d{8})")], axis=1))
)
              raw   name      date
0   name_20200304   name  20200304
1  other_20200305  other  20200305

但我希望获得一种更直接的方式来获得此“提取并追加”操作。

1 个答案:

答案 0 :(得分:1)

您可以尝试:

In [53]: pd.DataFrame({'raw': ['name_20200304', 'other_20200305']})
Out[53]:
              raw
0   name_20200304
1  other_20200305

In [54]: df = pd.DataFrame({'raw': ['name_20200304', 'other_20200305']})

In [55]: df[['name','date']]= df['raw'].str.split("_",expand=True)

In [56]: df
Out[56]:
              raw   name      date
0   name_20200304   name  20200304
1  other_20200305  other  20200305