How to fill in rows with repeating data in pandas?

前端 未结 7 449
感情败类
感情败类 2021-01-02 02:59

In R, when adding new data of unequal length to a data frame, the values repeat to fill the data frame:

df <- data.frame(first=c(1,2,3,4,5,6))
df$second &         


        
7条回答
  •  被撕碎了的回忆
    2021-01-02 03:23

    In my case I needed to repeat the values without knowing the length of the sub-list, i.e. checking the length of every group. This was my solution:

    import numpy as np
    import pandas 
    
    df = pandas.DataFrame(['a','a','a','b','b','b','b'], columns=['first'])
    
    list = df.groupby('first').apply(lambda x: range(len(x))).tolist()
    loop = [val for sublist in list for val in sublist]
    df['second']=loop
    
    df
      first  second
    0     a       0
    1     a       1
    2     a       2
    3     b       0
    4     b       1
    5     b       2
    6     b       3
    

提交回复
热议问题