Professional Documents
Culture Documents
data
between
csv files
RAJIB CHAKRABORTY
The acronym CSV is short for Comma-Separated Values. The CSV
format refers to a tabular data that has been saved as plaintext where
data is separated by commas. For example consider a table having
some data as shown below. If you store this table’s data in CSV format
then the data of the table will be stored in CSV format as shown below.
Output:
Reading CSV file and Specifying Own Column Names
Sometimes you may have a CSV file that does not have top row
containing column headers (as shown below).
Now if you read such a file, it will take the top row as the column
headers.
Example : Output:
Example :
Output:
This time it has not taken first row
as headings. First row remains data
and the column headings are as per
names parameters sequence.
Reading specified number of Rows from CSV file
You can read the specified number of rows from the CSV file by giving
nrows argument.
Example :
Output:
Because of argument nrows = 2,
only two rows have been read from
CSV file.
Reading from CSV files having different Separator from comma
Example :
Output:
Storing Dataframe’s Data to CSV File
Sometimes, we have data available in dataframes and we want to save
that data in a CSV file. For this purpose Python provides to_csv( )
function.
Example : DataFrame ( df )
Storing Dataframe’s Data to CSV File with separator as ‘|’
We can save the dataframe’s data to a CSV file with separator as ‘|’.
Example : DataFrame ( df )
Handling NaN Values with to_csv( )
Sometimes, your dataframe contains missing (NaN) values.
Example : DataFrame df with NaN values
Now, if you store this dataframe in a CSV file by giving the following
command :
Example :
The stud3.csv file will look like as shown below.