,我有以下的數據幀:快速地列拆分成多行大熊貓
import pandas as pd
df = pd.DataFrame({ 'gene':["foo",
"bar // lal",
"qux",
"woz"], 'cell1':[5,9,1,7], 'cell2':[12,90,13,87]})
df = df[["gene","cell1","cell2"]]
df
,看起來像這樣:
Out[6]:
gene cell1 cell2
0 foo 5 12
1 bar // lal 9 90
2 qux 1 13
3 woz 7 87
我想要做的是分裂的「基因「一欄中,這樣就會導致這樣的:
gene cell1 cell2
foo 5 12
bar 9 90
lal 9 90
qux 1 13
woz 7 87
我目前的做法是這樣的:
import pandas as pd
import timeit
def create():
df = pd.DataFrame({ 'gene':["foo",
"bar // lal",
"qux",
"woz"], 'cell1':[5,9,1,7], 'cell2':[12,90,13,87]})
df = df[["gene","cell1","cell2"]]
s = df["gene"].str.split(' // ').apply(pd.Series,1).stack()
s.index = s.index.droplevel(-1)
s.name = "Genes"
del df["gene"]
df.join(s)
if __name__ == '__main__':
print(timeit.timeit("create()", setup="from __main__ import create", number=100))
# 0.608163118362
這是非常慢很慢。實際上我有大約40K行來檢查 和進程。
這是什麼快速實現?
我猜測緩慢的部分是應用(而不是拆分或堆棧)? –
是的,我同意,只要你開始在數據框上進行字符串操作,我認爲你開始看到一些減速。不過,在這一點上我想不出什麼才華橫溢。既然你知道你想讓兩行(對於bar // lal)具有相同的值,也許你可以在你的數據框中添加另一行,就像'bar'行一樣,但是使用'lal'。不知道它會更快! –