Consider the following Python code using pandas to write a DataFrame to a CSV file. What will be the content of the CSV file?
import pandas as pd df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]}) df.to_csv('output.csv', index=False)
Check the index parameter in to_csv and the default separator.
Since index=False, the row numbers are not saved. The default separator is a comma, so the CSV content has columns Name and Age separated by commas.
This code writes a DataFrame to a CSV file. How many rows (including header) will the CSV file have?
import pandas as pd df = pd.DataFrame({'City': ['NY', 'LA', 'Chicago'], 'Population': [8000000, 4000000, 2700000]}) df.to_csv('cities.csv', index=True)
Remember that index=True adds an index column and the header row is also counted.
The DataFrame has 3 rows. With index=True, the index is saved as a column. The CSV includes a header row, so total rows = 3 data rows + 1 header = 4.
Look at this code snippet. What error will it raise when executed?
import pandas as pd df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) df.to_csv('data.csv', sep=';') df.to_csv('data.csv', sep=',', header=False, index=False, mode='x')
Check the meaning of mode='x' when opening files.
The first to_csv creates 'data.csv'. The second call uses mode='x', which tries to create a new file but fails if the file exists, raising FileExistsError.
You want to save a DataFrame to a CSV file using a tab character as separator and without writing the header row. Which code does this correctly?
import pandas as pd df = pd.DataFrame({'X': [10, 20], 'Y': [30, 40]})
Check the parameters sep and header in to_csv.
Option A sets sep='\t' for tab separator and header=False to omit the header row. This matches the requirement exactly.
line_terminator='\r\n' in to_csv?When writing a CSV file with pandas to_csv, what does setting line_terminator='\r\n' do?
Think about different operating systems and their line ending conventions.
Windows uses carriage return + line feed (\r\n) as line endings. Setting line_terminator='\r\n' makes the CSV use Windows-style line breaks instead of the default Unix-style \n.