2016-11-23 113 views
2

如何在Excel或csv中插入一個空行來分隔每個組。目前我正在使用熊貓,我不打包這樣做。向python中的csv或excel文件添加一個空行,並將其排到python

當前表:

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中是可以實現的。

回答

2

您可以使用帶自定義功能的groupby添加最後一個空行。最後使用to_csv,參數index=False忽略index

注意:

之前寫csvdf投地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) 
+0

當然,請檢查編輯。 – jezrael

+0

它是如何工作的? – jezrael

+0

是的,它寫入excel的時候工作。非常感謝 – Balaji

相關問題