prompt mine App
Find, Create & Share AI Magic
Enhanced Python Code for CSV to JSON Conversion
Create a Python code snippet that reads data from a CSV file named 'data.csv', transforms the data by converting the 'date' column to datetime format and removing any rows with missing values, converts the CSV data into a list of dictionaries, and saves the output as a JSON file named 'data.json'.
The Python code snippet should utilize the pandas library to read the CSV file, perform data cleaning and transformations, and then use the json library to convert the data into a list of dictionaries and save it as a JSON file.
Here's an example implementation:
python
import pandas as pd
import json
Read the CSV file
def read_csv(filename):
try:
data = pd.read_csv(filename)
return data
except Exception as e:
print(f"Error reading CSV file: {e}")
Transform the data
def transform_data(data):
Convert 'date' column to datetime format
data['date'] = pd.to_datetime(data['date'])
Remove any rows with missing values
data = data.dropna()
return data
Convert CSV data to JSON
def csv_to_json(data):
json_data = data.to_dict(orient='records')
return json_data
Save JSON data to a file
def save_json(json_data, filename):
with open(filename, 'w') as f:
json.dump(json_data, f, indent=4)
Main function
def main():
filename = 'data.csv'
data = read_csv(filename)
if data is not None:
transformed_data = transform_data(data)
json_data = csv_to_json(transformed_data)
save_json(json_data, 'data.json')
print("CSV data successfully converted to JSON and saved to data.json")
if __name__ == "__main__":
main()
Example CSV data:
csv
id,name,date,age
1,John,2022-01-01,25
2,Jane,2022-01-02,30
3,Bob,2022-01-03,35
This code snippet assumes that the CSV file has a 'date' column and that the data should be transformed by converting this column to datetime format and removing any rows with missing values. The resulting JSON data will be a list of dictionaries, where each dictionary represents a row from the CSV file. The JSON data will be saved to a file named 'data.json'.

Find Powerful AI Prompts
Discover, create, and customize prompts with different models, from ChatGPT to Gemini in seconds

Simple Yet Powerful
Start with an idea and use expert prompts to bring your vision to life!