繁体   English   中英

在Pandas DataFrame中快速拆分特定列的行

[英]Fast split rows of a specific column in Pandas DataFrame

我有以下数据框:

import pandas as pd
df = pd.DataFrame({'Probes':["1415693_at","1415693_at"],
                   'Genes':["Canx","LOC101056688 /// Wars "],
                   'cv_filter':[ 0.134,0.290],
                   'Organ' :["LN","LV"]}   )    
df = df[["Probes","Genes","cv_filter","Organ"]]  

看起来像这样:

In [16]: df
Out[16]:
       Probes                   Genes  cv_filter Organ
0  1415693_at                    Canx      0.134    LN
1  1415693_at  LOC101056688 /// Wars       0.290    LV

我想要做的是基于“基因”列拆分行,在该列中,条目以“ ///”分隔。

我想要得到的结果是

       Probes                   Genes  cv_filter Organ
0  1415693_at                    Canx      0.134    LN
1  1415693_at            LOC101056688      0.290    LV
2  1415693_at                    Wars      0.290    LV

我总共要检查约15万行。 有没有一种快速的方法来处理呢?

您可以尝试第一个str.splitGenes ,创建新的Series并将其join到原始df

import pandas as pd
df = pd.DataFrame({'Probes':["1415693_at","1415693_at"],
                   'Genes':["Canx","LOC101056688 /// Wars "],
                   'cv_filter':[ 0.134,0.290],
                   'Organ' :["LN","LV"]}   )    
df = df[["Probes","Genes","cv_filter","Organ"]]  
print df
       Probes                   Genes  cv_filter Organ
0  1415693_at                    Canx      0.134    LN
1  1415693_at  LOC101056688 /// Wars       0.290    LV

s = pd.DataFrame([ x.split('///') for x in df['Genes'].tolist() ], index=df.index).stack()
#or you can use approach from comment
#s = df['Genes'].str.split('///', expand=True).stack()

s.index = s.index.droplevel(-1) 
s.name = 'Genes' 
print s
0             Canx
1    LOC101056688 
1            Wars 
Name: Genes, dtype: object

#remove original columns, because error:
#ValueError: columns overlap but no suffix specified: Index([u'Genes'], dtype='object')    
df = df.drop('Genes', axis=1)

df = df.join(s).reset_index(drop=True)
print df[["Probes","Genes","cv_filter","Organ"]] 
       Probes          Genes  cv_filter Organ
0  1415693_at           Canx      0.134    LN
1  1415693_at  LOC101056688       0.290    LV
2  1415693_at          Wars       0.290    LV

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM