Fast way to split column into multiple rows in Pandas

后端 未结 3 1447
南笙
南笙 2021-02-02 00:07

I have the following data frame:

import pandas as pd
df = pd.DataFrame({ \'gene\':[\"foo\",
                            \"bar // lal\",
                                  


        
3条回答
  •  遇见更好的自我
    2021-02-02 00:18

    We can first split the column, expand it, stack it and then join it back to the original df like below:

    df.drop('gene', axis=1).join(df['gene'].str.split('//', expand=True).stack().reset_index(level=1, drop=True).rename('gene'))
    

    which gives us this:

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

提交回复
热议问题