Cyb*_*ube 4 python dataframe python-3.x pandas
我有一个名为“因子”的列,每次该列中的名称更改时,我想插入一个空白行,这可能吗?
for i in range(0, end):
if df2.at[i + 1, 'factor'] != df2.at[i, 'factor']:
Run Code Online (Sandbox Code Playgroud)
在for
循环中按顺序手动插入行是低效的。作为替代方案,您可以找到发生变化的索引,构建一个新的数据框,连接,然后按索引排序:
df = pd.DataFrame([[1, 1], [2, 1], [3, 2], [4, 2],
[5, 2], [6, 3]], columns=['A', 'B'])
switches = df['B'].ne(df['B'].shift(-1))
idx = switches[switches].index
df_new = pd.DataFrame(index=idx + 0.5)
df = pd.concat([df, df_new]).sort_index()
print(df)
A B
0.0 1.0 1.0
1.0 2.0 1.0
1.5 NaN NaN
2.0 3.0 2.0
3.0 4.0 2.0
4.0 5.0 2.0
4.5 NaN NaN
5.0 6.0 3.0
5.5 NaN NaN
Run Code Online (Sandbox Code Playgroud)
如有必要,您可以使用reset_index
来规范化索引:
print(df.reset_index(drop=True))
A B
0 1.0 1.0
1 2.0 1.0
2 NaN NaN
3 3.0 2.0
4 4.0 2.0
5 5.0 2.0
6 NaN NaN
7 6.0 3.0
8 NaN NaN
Run Code Online (Sandbox Code Playgroud)