War*_*ior 6 python dataframe pandas
我想创建一个新列,每 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。我希望处理更通用的代码。
这是一种创建蒙版的Dataframe.groupby.cumcount方法。pandas.Series.shift使用掩码来填充col2和col1使用Series.ffill缺失值。
g = df.groupby(df.index % 4).cumcount()
mask = g.ne(g.shift(1))
0 True
1 False
2 False
3 False
4 True
5 False
6 False
7 False
8 True
dtype: bool
Run Code Online (Sandbox Code Playgroud)
df.loc[mask, 'col2'] = df.loc[mask, 'col1']
col1 col2
0 1 1.0
1 2 NaN
2 3 NaN
3 4 NaN
4 5 5.0
5 6 NaN
6 7 NaN
7 8 NaN
8 9 9.0
Run Code Online (Sandbox Code Playgroud)
df['col2'].ffill(inplace=True)
col1 col2
0 1 1.0
1 2 1.0
2 3 1.0
3 4 1.0
4 5 5.0
5 6 5.0
6 7 5.0
7 8 5.0
8 9 9.0
Run Code Online (Sandbox Code Playgroud)