【问题标题】:Adding an empty row with group wise to csv or excel file in python在 python 中向 csv 或 excel 文件中添加一个具有分组明智的空行
【发布时间】:2017-04-07 02:26:23
【问题描述】:

如何在 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

_

想要的表

注意:每个不同列之后的空白行1

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 中实现它。

【问题讨论】:

    标签: python excel csv pandas


    【解决方案1】:

    您可以将groupby 与添加最后一个空行的自定义函数一起使用。最后使用to_csv 和参数index=False 来忽略index

    注意:

    在写入csv 之前是df 转换为string,因为如果添加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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 2018-03-08
      相关资源
      最近更新 更多