Kevin
Kevin

Reputation: 71

Pandas Dataframe to CSV, but writing n rows lower

Given a 3x3 dataframe, with index and column names to be included as a row/column themselves when converting the dataframe to a CSV file, how can I shift the table down 1 row?

I want to shift down 1 row, leaving 1 empty row to write to the CSV after using a completely separate list.

The code and comments below include more detail and clarity regarding my goal:

import pandas as pd
separate_row = [' ', 'Z', 'Y', 'X']

# Note: The size is 3x3
x = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
header_cols = ['a','b','c']
df = pd.DataFrame(x, index=[1,2,3], columns=header_cols)

# Note: Exporting as 4x4 now
df.to_csv('data.csv', index=True, header=True)

# How to make CSV file 5x4??

Row 1 in the CSV file will be filled by separate_row, though I cannot have separate_row as the column name when creating the dataframe. The column name MUST be header_cols but separate_row is to go above.

Upvotes: 1

Views: 1237

Answers (2)

Corralien
Corralien

Reputation: 120391

Try:

with open('data.csv', 'w') as csvfile:
    pd.DataFrame(columns=separate_row).to_csv(csvfile, index=None)
    df.to_csv(csvfile, index=True, header=True)
>>> %cat data.csv
 ,Z,Y,X
,a,b,c
1,0,0,0
2,0,0,0
3,0,0,0

Upvotes: 1

Chris
Chris

Reputation: 16147

You could write a newline to a file, then append the dataframe:

import pandas as pd

# Note: The size is 3x3
x = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
df = pd.DataFrame(x, index=[1,2,3], columns=['a','b','c'])



with open('data.csv', 'w') as f:
    f.write('\n')


df.to_csv('data.csv', index=True, header=True, mode='a')

Upvotes: 0

Related Questions