Split (explode) pandas dataframe string entry to separate rows

后端 未结 22 3554
一向
一向 2020-11-21 05:03

I have a pandas dataframe in which one column of text strings contains comma-separated values. I want to split each CSV field and create a new row per entry (as

22条回答
  •  不思量自难忘°
    2020-11-21 05:12

    Similar question as: pandas: How do I split text in a column into multiple rows?

    You could do:

    >> a=pd.DataFrame({"var1":"a,b,c d,e,f".split(),"var2":[1,2]})
    >> s = a.var1.str.split(",").apply(pd.Series, 1).stack()
    >> s.index = s.index.droplevel(-1)
    >> del a['var1']
    >> a.join(s)
       var2 var1
    0     1    a
    0     1    b
    0     1    c
    1     2    d
    1     2    e
    1     2    f
    

提交回复
热议问题