suppose I have the following csv file called mycsv.csv
"Date" "order 1" "order 2" "order 3" "total cost"
01/04/2006 4 tires 1 oil 6 sparks plugs "434.00$'
03/08/2006 3 tires 2 oil 2 sparks plugs "234.00$'
03/12/2006 2 tires 0 oil 1 sparks plugs "134.00$'
I want to know how to store the those data in a 2d array, any help will be greatly appreciated!
break each record into the one dimension array. for loop inside the first loop along to the number of columns in csv file. Assigned each value from the one dimension array into the two dimension array.
Line 1: We import the NumPy library. Line 3-4: We open the sampleCSV file and we pass both CSVData and the delimiter to np. loadtxt () function, which returns the data into a 2D array. Line 6: We finally print the result which shows that now our CSV data converted into a 2D array.
Python NumPy read CSV into 2d NumPy arraytxt() and open() functions to load a CSV file into a 2Dimension NumPy Array. Call open file to open the CSV text file Use numpy. loadtxt( CSV file, delimiter) with the file as the result of the previous step and delimiter as “,” to return the data in a two-dimensional NumPy.
You might use fgetcsv
(see: http://php.net/manual/en/function.fgetcsv.php). The difference to str_getcsv
is that it takes a File resource
as parameter and not a String
.
You might also store each row in another Array to have a 2D Array e.g. (adjusted manual page example)
$twoDarray = array();
if (($handle = fopen("mycsv.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$twoDarray[] = $data;
}
fclose($handle);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With