WRITE A PROGRAM ON PURE PYTHON WITHOUT USING ANY LIBRARIES LIKE PANDAS AND NUMPY
- Read a CSV file 'annual.csv' enterprise into a data structure
- Count the number of rows and columns
- Determine if the data contains empty values
- Replace the empty values by 'NA' for strings, '0' for decimals and '0.0' for floats
- Transform all Upper case characters to Lower case characters
- Transform all Lower case characters to Upper case characters
- save back the 'repaired' array as csv
- Print out the size of the data (number of rows, number of columns)
Difficulty:
-- be sure that each row has the same length (number of elements)
- the length of each row should be the same as the header.
AGAIN, program should be written in python, without any additional libraries
Please look at my code and in case of indentation issues check the screenshots.
------------main.py----------------
import csv
def transformString(s): #this function reads a
string, convertes lc to uc and uc to lc chars
s1 = ""
for char in s:
if char.islower():
#checks lowercase
s1 +=
char.upper() #converts to
uppercase
elif char.isupper():
#checks uppercase
s1 +=
char.lower() #converts to
lowercase
else:
s1 += char
return s1
def main():
f = open("annual.csv", "r")
#reads csv
reader = csv.reader(f)
header = next(reader)
#reads the heading
output_list = [header]
#adds the heading in the output_list
for row in reader:
#reads remaining rows one by
one
row[0] =
transformString(row[0]) #transforms column 1 element,
since it is a string
if row[0] == "":
#replaces empty strings, with NA
row[0] =
"NA"
if row[1] == "":
#replaces empty integers with 0
row[1] = 0
if row[2] == "":
#replaces empty floats with 0.0
row[2] =
0.0
output_list.append([row[0],
int(row[1]), float(row[2])]) #adds row to
output_list
w = open("annual_repaired", 'w')
#opens csv for writing
writer = csv.writer(w)
writer.writerows(output_list)
#writes the output_list
print("ROWS: ", len(output_list), "COLUMNS: ",
len(header))
print("annual_repaired.csv created
successfully!!!")
main()
--------------Screenshots-------
------------Input-------------
------------Output-------------
------------------------------------------------------------------------------------
Please give a thumbs up if you find this answer helpful.
If it doesn't help, please comment before giving a thumbs
down.
Please Do comment if you need any clarification.
I will surely help you.
Thankyou
Get Answers For Free
Most questions answered within 1 hours.