在python中将带有group wise的空行添加到csv或excel文件

在python中将带有group wise的空行添加到csv或excel文件,python,excel,csv,pandas,Python,Excel,Csv,Pandas,如何在excel或csv中插入空行分隔每个组。目前我正在使用熊猫,我不想这样做 当前表格: column1 | column2 | column3 ---------------------------------- A | 23 | blue A | 23 | orange A | 45 | yellow A | 45 | yellow A

如何在excel或csv中插入空行分隔每个组。目前我正在使用熊猫,我不想这样做

当前表格:

column1   |   column2   |  column3
----------------------------------
  A       |     23     |  blue
  A       |     23     |  orange
  A       |     45     |  yellow
  A       |     45     |  yellow
  A       |     45     |  blue
  A       |     60     |  green
  A       |     60     |  green
  A       |     75     |  pink
_

所需表格

注:每一个不同的Calnn

后的空白行
column1   |   column2   |  column3
----------------------------------
  A       |     23     |  blue
  A       |     23     |  orange

  A       |     45     |  yellow
  A       |     45     |  yellow
  A       |     45     |  blue

  A       |     60     |  green
  A       |     60     |  green

  A       |     75     |  pink
有谁能告诉我如何在python中实现它。

您可以在自定义函数中使用添加最后一个空行。上次与参数
index=False一起使用时,忽略
index

注意:

在写入
csv
之前,将
df
转换为
string
,因为如果添加
NaN
行,所有整数列都将转换为
float


对于excel使用:

def f(x):
    x.loc[-1] = pd.Series([])
    return x
df = df.astype(str).groupby(['column1','column2'], as_index=False).apply(f)

print (df)
     column1 column2 column3
0  0       A      23    blue
   1       A      23  orange
  -1     NaN     NaN     NaN
1  2       A      45  yellow
   3       A      45  yellow
   4       A      45    blue
  -1     NaN     NaN     NaN
2  5       A      60   green
   6       A      60   green
  -1     NaN     NaN     NaN
3  7       A      75    pink
  -1     NaN     NaN     NaN

#default separator is ,
df.to_csv('file.csv', index=False)
A,23,blue
A,23,orange
,,
A,45,yellow
A,45,yellow
A,45,blue
,,
A,60,green
A,60,green
,,
A,75,pink
,,
#custom separator tab
df.to_csv('file.csv', index=False, sep='\t')
column1 column2 column3
A       23      blue
A       23      orange

A       45      yellow
A       45      yellow
A       45      blue

A       60      green
A       60      green

A       75      pink
df.to_excel('file.xlsx', index=False)