当列中的值更改时,在Python数据框中插入空白行? [英] Insert Blank Row In Python Data frame when value in column changes?
问题描述
我有一个数据框,每当第一列中的值更改时,我都想插入一个空白行作为分隔符.
I have a dataframe and I'd like to insert a blank row as a separator whenever the value in the first column changes.
例如:
Column 1 Col2 Col3 Col4
A s b d
A s j k
A b d q
B b a d
C l k p
成为:
Column 1 Col2 Col3 Col4
A s b d
A s j k
A b d q
B b a d
C l k p
因为第1列中的值已更改
because the value in Column 1 changed
我弄清楚如何做到这一点的唯一方法是使用VBA,如此处正确标记的答案所示:
The only way that I figured out how to do this is using VBA as indicated by the correctly marked answer here:
但是我需要在Python中执行此操作.
But I need to do this in Python.
任何帮助将不胜感激!
推荐答案
使用最近更改的索引值创建帮助器DataFrame
,添加.5
,并通过 sort_index
,通过 iloc
:
Create helper DataFrame
with index values of last changes, add .5
, join together with original by concat
, sorting indices by sort_index
, create default index by reset_index
and lasr remove last row by positions with iloc
:
mask = df['Column 1'].ne(df['Column 1'].shift(-1))
df1 = pd.DataFrame('',index=mask.index[mask] + .5, columns=df.columns)
df = pd.concat([df, df1]).sort_index().reset_index(drop=True).iloc[:-1]
print (df)
Column 1 Col2 Col3 Col4
0 A s b d
1 A s j k
2 A b d q
3
4 B b a d
5
6 C l k p
这篇关于当列中的值更改时,在Python数据框中插入空白行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!