【问题标题】:I want to replace data continuously by the number of specific columns我想用特定列的数量连续替换数据
【发布时间】:2020-05-28 20:51:49
【问题描述】:

我想根据我的数据框中的特定列连续替换原始值,如下所示。

输入,

预期输出,

我试图这样解决它,但没有奏效。你能帮帮我吗?

df = data
df1 = df[:]    

a = 0
while a <= df.shape[0]:
    if pd.isnull(df['REPEAT'].iloc[a]) == False :
        for j in range(int(df['REPEAT'].iloc[a])) : 
            df1.iloc[a+j] = df.iloc[a]
    a = a+j+1

【问题讨论】:

    标签: python dataframe preprocessor


    【解决方案1】:

    您可以将fillnaffil 方法一起使用

    df.fillna(method='ffil')
    

    更多详情请看link
    在您的情况下,您可以尝试以下代码:

    i = 0
    while i < df.shape[0]:
        if not np.isnan(df.loc[i,"REPEAT"]):
            rep = int(df.iloc[i]["REPEAT"])
            df.loc[i+1:i+rep,"A"] = df.iloc[i]["A"]
            df.loc[i+1:i+rep,"b"] = df.iloc[i]["b"]
            df.loc[i+1:i+rep,"REPEAT"] = rep
            i = i + rep
        i = i + 1
    

    但如果 date_time 是您的数据帧的索引,您必须在尝试此代码之前重置索引

    【讨论】:

    • 这可能不会导致 OP 需要这将填充所有行,您可能需要应用 loc 过滤器。
    • @Sushanth 我通过添加他的案例的解决方案来编辑​​答案
    • 我从你的回答中得到了这个想法并像这样解决了它。谢谢。
    • df = data[:] df1= df[:] i = 0 while i
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    相关资源
    最近更新 更多