Here's a Python code that takes a CSV file as input, removes the string part from the entries in columns 9 and 10 if they are mixed with floats, and writes the modified data to a new CSV file:
import csv
def process_csv(input_file, output_file):
with open(input_file, 'r') as file:
reader = csv.reader(file)
rows = list(reader)
for row in rows[1:]: # Skip the header row
for i in [8, 9]: # Columns 9 and 10 (index 8 and 9)
if row[i]:
try:
float_value = float(row[i])
row[i] = str(float_value)
except ValueError:
row[i] = ''
with open(output_file, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(rows)
# Example usage
input_file = 'input.csv'
output_file = 'output.csv'
process_csv(input_file, output_file)
Explanation:
-
We import the csv module to work with CSV files.
-
We define a function called process_csv that takes two parameters: input_file (the path to the input CSV file) and output_file (the path to the output CSV file).
-
We open the input CSV file in read mode using open() and create a csv.reader object to read the CSV data.
-
We convert the CSV data to a list of rows using list(reader) for easier manipulation.
-
We iterate over each row in the rows list, starting from index 1 to skip the header row.
-
For each row, we focus on columns 9 and 10 (index 8 and 9 in the row list).
-
We check if the entry in each column is not empty using an if statement.
-
If the entry is not empty, we use a try-except block to attempt to convert the entry to a float using float().
- If the conversion is successful, we update the entry in the row with the float value converted back to a string using
str().
- If the conversion raises a
ValueError (indicating the presence of a string), we replace the entry with an empty string.
-
After processing all the rows, we open the output CSV file in write mode using open() with the 'w' flag and newline='' to avoid extra newlines.
-
We create a csv.writer object to write the modified data to the output CSV file.
-
We use the writerows() method of the CSV writer to write all the rows to the output file.
-
Finally, we provide an example usage of the process_csv function by specifying the input and output file paths.
This code will read the input CSV file, remove the string part from the entries in columns 9 and 10 if they are mixed with floats, and write the modified data to the output CSV file. The resulting CSV file will have the string parts removed from those columns, leaving only the float values (or an empty string if no float value is present).