首页 > 解决方案 > 将 pandas 数据帧重新采样到任意数量

问题描述

我有一个循环,其中在每个步骤中都用值填充了一个新的数据框。对于循环中的每个步骤,新数据框中的行数是不同的。在循环结束时,我想比较数据帧,为此,它们都需要具有相同的长度。有没有办法可以在每一步将数据帧重新采样为任意数量(例如 5618)的行?

标签: pythonpandasloopsdataframeresampling

解决方案


If your dataframe is too small by N rows, then you can randomly sample N rows with replacement and add the rows on to the end of your original dataframe. If your dataframe is too big, then sample the desired number from the original dataframe .

if len(df) <5618:
    df1 = df.sample(n=5618-len(df),replace=True)
    df = pd.concat([df,df1])
if len(df) > 5618:
    df = df.sample(n=5618)

推荐阅读