pandas 由最后一个分隔符分割 [英] pandas split by last delimiter

查看:119
本文介绍了 pandas 由最后一个分隔符分割的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据框中具有不同输出的以下列"

I have the following column in a dataframe with different outputs"

col1
MLB|NBA|NFL
MLB|NBA
NFL|NHL|NBA|MLB

我想始终使用split函数按最后一个管道拆分列,如下所示:

I would like to use the split function to split the column by the last pipe always so something like this:

col1           col2
MLB|NBA        NFL
MLB            NBA
NFL|NHL|NBA    MLB

推荐答案

使用Series.str.rsplit,限制拆分次数.

df.col1.str.rsplit('|', 1, expand=True).rename(lambda x: f'col{x + 1}', axis=1)

如果以上内容引发了SyntaxError错误,则意味着您使用的Python版本早于3.6(可耻!).改用

If the above throws you a SyntaxError, it means you're on a python version older than 3.6 (shame on you!). Use instead

df.col1.str.rsplit('|', 1, expand=True)\
  .rename(columns=lambda x: 'col{}'.format(x + 1))

          col1 col2
0      MLB|NBA  NFL
1          MLB  NBA
2  NFL|NHL|NBA  MLB


还有更快的循环str.rsplit等效项.


There's also the faster loopy str.rsplit equivalent.

pd.DataFrame(
    [x.rsplit('|', 1) for x in df.col1.tolist()], 
    columns=['col1', 'col2']
) 
          col1 col2
0      MLB|NBA  NFL
1          MLB  NBA
2  NFL|NHL|NBA  MLB


P.S.,是的,第二种解决方案更快:


P.S., yes, the second solution is faster:

df = pd.concat([df] * 100000, ignore_index=True)

%timeit df.col1.str.rsplit('|', 1, expand=True)
%timeit pd.DataFrame([x.rsplit('|', 1) for x in df.col1.tolist()])

473 ms ± 13.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
128 ms ± 1.29 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

这篇关于 pandas 由最后一个分隔符分割的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆