Skip to content Skip to sidebar Skip to footer

How To Loop List Value Of A Specific Column In Pandas?

I have a pandas dataframe, which the first column are list values. I want to loop each str value of each list, and the values of next columns will be in included together. For exam

Solution 1:

I think you can use numpy.repeat for repeat values by legths by str.len and flat values of nested lists by chain:

fromitertoolsimportchainlens=tm.author.str.len()df=pd.DataFrame({"date":np.repeat(tm.date.values,lens),"journal":np.repeat(tm.journal.values,lens),"author":list(chain.from_iterable(tm.author))})print(df)authordatejournal0author_a12015-02-03  journal011author_a22015-02-03  journal012author_a32015-02-03  journal013author_b12015-02-04  journal024author_b22015-02-04  journal025author_c12015-02-05  journal036author_c22015-02-05  journal03

Another numpy solution:

df = pd.DataFrame(np.column_stack((tm[['date','journal']].values.\
     repeat(list(map(len,tm.author)),axis=0) ,np.hstack(tm.author))), 
     columns=['date','journal','author'])

print (df)
                  date    journal     author
02015-02-0300:00:00  journal01  auther_a1
12015-02-0300:00:00  journal01  auther_a2
22015-02-0300:00:00  journal01  auther_a3
32015-02-0400:00:00  journal02  auther_b1
42015-02-0400:00:00  journal02  auther_b2
52015-02-0500:00:00  journal03  auther_c1
62015-02-0500:00:00  journal03  auther_c2

Post a Comment for "How To Loop List Value Of A Specific Column In Pandas?"