How to fill in rows with repeating data in pandas?

前端 未结 7 512
感情败类
感情败类 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:21

    Probably inefficient, but here's sort of a pure pandas solution.

    import numpy as np
    import pandas as pd
    
    base = [1,2,3]
    df = pd.DataFrame(data = None,index = np.arange(10),columns = ["filler"])
    df["filler"][:len(base)] = base
    
    df["tmp"] = np.arange(len(df)) % len(base)
    df["filler"] = df.sort_values("tmp")["filler"].ffill() #.sort_index()
    print(df)
    

提交回复
热议问题