6
votes

I am reading in a CSV file as a DataFrame while defining each column's data type. This code gives an error if the CSV file has a blank row in it. How do I read the CSV without blank rows?

dtype = {'material_id': object, 'location_id' : object, 'time_period_id' : int, 'demand' : int, 'sales_branch' : object, 'demand_type' : object }

df = pd.read_csv('./demand.csv', dtype = dtype)

I thought of one workaround of doing something like this but not sure if this is the efficient way:

df=pd.read_csv('demand.csv')
df=df.dropna()

and then redefining the column data types in the df.

Edit : Code -

import pandas as pd
dtype1 = {'material_id': object, 'location_id' : object, 'time_period_id' : int, 'demand' : int, 'sales_branch' : object, 'demand_type' : object }
df = pd.read_csv('./demand.csv', dtype = dtype1)
df

Error - ValueError: Integer column has NA values in column 2

My CSV file's snapshot - enter image description here

5
Could you provide the error? An example that I have tried in this dataset: owner,car Pedro,Honda Antonio,Hyunday When I execute this code: cars_df = pd.read_csv('cars.csv') This code works despite there is a blank row: owner car 0 Pedro Honda 1 Antonio Hyunday - Antonio Andrés
Please include a snippet of your demand.csv with some blank lines, to reproduce the issue and make this a MCVE (Minimum Complete Verifiable Example). Otherwise, noone can reproduce your issue. You might like to use multiline strings: """A B C\n1 2 3.4\n...""" and read using StringIO. - smci
Please check your whole file that all rows that got any data in it also have an integer value in time_period (column 2). The Error states that you got a NA value in column 2 - so probably there are some non-int characters in column 2 somewhere. Also: open CSV in notepad++ or smth alike - NOT Excel/OpenOffice/LibreOffice. That way you can see the delimiters as well. There might be rows that only consist of ,,,,, which would be a filled row but with all empty values. - Patrick Artner
pandas by default populates the empty row as NaN. Could that be causing the problem? - Karvy1
Yes, I see the empty row as ,,,,, - Karvy1

5 Answers

4
votes

This worked for me.

def delete_empty_rows(file_path, new_file_path):
    data = pd.read_csv(file_path, skip_blank_lines=True)
    data.dropna(how="all", inplace=True)
    data.to_csv(new_file_path, header=True)
1
votes

try smth like this:

data = pd.read_table(filenames,skip_blank_lines=True, a_filter=True)
0
votes

solution could be :

data = pd.read_table(filenames,skip_blank_lines=True, na_filter=True)
-3
votes

try.csv

s,v,h,h
1,2,3,4

4,5,6,7



9,10,1,2

Python Code

df = pd.read_csv('try.csv', delimiter=',')
print(df)

Output

   s   v  h  h.1
0  1   2  3    4
1  4   5  6    7
2  9  10  1    2
-3
votes

I am not sure whether its efficient or not but it works. This code does not load nan values while reading a csv.

df=pd.read_csv('demand.csv').dropna()