Python: How to Check If Cell in CSV File Is Empty

Python: How to check if cell in CSV file is empty?

with open('testdata1.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
if not row[0]:

How do I detect missing fields in a CSV file in a Pythonic way?

Checking if the first cell of a CSV is blank in Python

I was able to get this to work:

with open('some_file.csv', 'a', newline='') as csv_a, open('some_file.csv','r') as csv_r:
reader = csv.reader(csv_r)
writer = csv.DictWriter(csv_a, sorted_closes.keys())
data = [row for row in reader] #turns all the cells into a list
if data[0][0]=='':
# or whatever you want to do if the first cell is empty
# or whatever you want to do if the first cell is NOT empty

Empty cell in csv not detected in python

That column was supposed to have numerical data type, but it got identified as object because it has several empty cells.

This suggest that they are empty strings, ''. You could replace them with NaN values using replace:

df = df.replace('', np.nan)

How to check if .xls and .csv files are empty

This is simple in pandas with the .empty method. Do this

import pandas as pd

df = pd.read_csv(filename) # or pd.read_excel(filename) for xls file
df.empty # will return True if the dataframe is empty or False if not.

This will also return True for a file with only headers as in

>> df = pd.DataFrame(columns = ['A','B'])
>> df.empty

How to find and replace a value/string with the empty cell in CSV python

df.replace(to_replace ="C", value = "")

This will do the work.

How can I count empty cell in .csv file? if row['PredictionString']== " "

If submission is a pandas dataframe (like it seems to be), you can count like this:

counter1 = len(submission[submission.PredictionString == ' '])

Without any for loops.

Considering as empty ' ', '' and NaN's:

counter1 = len(submission[(submission.PredictionString == ' ') | (submission.PredictionString == '') | (submission.PredictionString.isnull())])


>> mydict = {'patientId': {0: '1', 1: '1', 2: '1'},
>> 'PredictionString': {0: '', 1: ' ', 2: np.NaN}}
>> submission = pd.DataFrame(mydict)
>> counter1 = len(submission[(submission.PredictionString == ' ') | (submission.PredictionString == '') | (submission.PredictionString.isnull())])
>> print(counter1)

Related Topics

Leave a reply