如何通过分隔符拆分 pandas 列并选择首选元素作为替换 [英] How to split pandas column by a delimiter and select preferred element as the replacement

查看:41
本文介绍了如何通过分隔符拆分 pandas 列并选择首选元素作为替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下熊猫数据框:

import pandas as pd
df = pd.DataFrame({ 'gene':["1 // foo // blabla",
                                   "2 // bar // lalala",
                                   "3 // qux // trilil",
                                   "4 // woz // hohoho"], 'cell1':[5,9,1,7], 'cell2':[12,90,13,87]})
df = source_df[["gene","cell1","cell2"]]

看起来像这样:

                 gene  cell1  cell2
0  1 // foo // blabla      5     12
1  2 // bar // lalala      9     90
2  3 // qux // trilil      1     13
3  4 // woz // hohoho      7     87

我想得到的是:

   gene    cell1  cell2
0   foo       5     12
1   bar       9     90
2   qux       1     13
3   woz       7     87

即以//为分隔符选择分割后的字符串的第2个元素.

Namely select 2nd element of the splited string by // as delimiter.

我能做的最好的是:

df["gene"] = df["gene"].str.split(" // ")
df
Out[17]:
               gene  cell1  cell2
0  [1, foo, blabla]      5     12
1  [2, bar, lalala]      9     90
2  [3, qux, trilil]      1     13
3  [4, woz, hohoho]      7     87

正确的做法是什么?

推荐答案

使用矢量化的 str.split 这将比使用 apply 快得多在大型数据集上:

Use the vectorised str.split this will be much faster than using apply on a large dataset:

In [13]:
df['gene'] = df['gene'].str.split('//').str[1]
df

Out[13]:
   cell1  cell2   gene
0      5     12   foo 
1      9     90   bar 
2      1     13   qux 
3      7     87   woz 

这篇关于如何通过分隔符拆分 pandas 列并选择首选元素作为替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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