我有以下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"]]
Run Code Online (Sandbox Code Playgroud)
它看起来像这样:
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
Run Code Online (Sandbox Code Playgroud)
我想得到的是:
gene cell1 cell2
0 foo 5 12
1 bar 9 90
2 qux 1 13
3 woz 7 87
Run Code Online (Sandbox Code Playgroud)
即通过//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
Run Code Online (Sandbox Code Playgroud)
什么是正确的方法呢?
EdC*_*ica 12
使用矢量化,str.split这比apply在大型数据集上使用要快得多:
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
Run Code Online (Sandbox Code Playgroud)