How to write a NumPy array with Numeric and String data to a CSV file?
2. CSV with Mixed Data Write
Write a NumPy array with both numeric and string data to a CSV file.
Sample Solution:
Python Code:
Output:
Data has been written to output.csv
Content of output.csv ---------------------------- 1,Jorah Liina,95.5 2,Basil Aisha,90.0 3,Helga Myrthe,80.0 4,Lehi Piero,91.5
Explanation:
- Import NumPy and CSV Libraries: Import the NumPy and CSV libraries to handle arrays and writing to CSV files.
- Create a NumPy Array: Define a NumPy array with mixed data types (both numeric and string data), specifying dtype=object to handle different types within the array.
- Define CSV File Path: Specify the path where the output CSV file will be saved.
- Write Array to CSV File: Open the CSV file in write mode using open() and csv.writer(). Iterate through each row of the NumPy array and write it to the CSV file using writer.writerow().
- Finally a message indicating that the data has been successfully written to the CSV file.
For more Practice: Solve these Related Problems:
- Write a Numpy program to export a mixed-type array (numeric and string) to a CSV file ensuring proper quoting of strings.
- Write a Numpy program to write a NumPy array containing both numbers and text to CSV and then verify the output by reading it back.
- Write a Numpy program to convert a structured array with numeric and string fields to CSV with custom delimiters.
- Write a Numpy program to write a mixed data NumPy array to CSV and then apply regex filtering on the exported file to extract numeric rows.
Go to:
Previous: How to read numeric data from a CSV file into a NumPy array?
Next: Convert Pandas DataFrame to NumPy array and print.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.