1

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.

2

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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')

1 Comment

It's not clear for me but I think the OP does not want a blank line, he wants the separate_row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.