使用Python向CSV或Excel文件中按组添加空行

3
如何在Excel或CSV中插入空行以分隔每个组。目前我正在使用pandas,但无法做到这一点。
当前表格:
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

希望的表格

注意:每个不同的column1之后要留出一个空行

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中实现吗?

1个回答

3
您可以使用自定义函数的groupby方法在最后添加空行。最后使用带有参数index=Falseto_csv 方法来忽略索引。
注意:
在写入csv之前,需要将df转换为字符串形式,因为如果添加了NaN行,则所有整数列都将转换为float
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

对于Excel使用,可以使用to_excel函数:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接