小编War*_*ior的帖子

每 4 行重复一次 value 并使用开始行填充其余行

我想创建一个新列,每 4 行重复另一列。使用起始行填充其间的行。例如对于df

d = {'col1': range(1,10)}
df = pd.DataFrame(data=d)
Run Code Online (Sandbox Code Playgroud)

我希望创建一个返回以下内容的col2:

col1    col2
1        1
2        1
3        1
4        1
5        5
6        5
7        5
8        5
9        9
Run Code Online (Sandbox Code Playgroud)

这是我试过的

df['col2'] = np.concatenate([np.repeat(df.col1.values[0::4], 4),
                             np.repeat(np.NaN, len(df)%3)])
Run Code Online (Sandbox Code Playgroud)

它产生错误: ValueError: Length of values does not match length of index

如果我将 4 更改为 3,则代码有效,因为len(df)是 9。我希望处理更通用的代码。

python dataframe pandas

6
推荐指数
1
解决办法
57
查看次数

标签 统计

dataframe ×1

pandas ×1

python ×1