How to Create a 2D Array from a CSV File

Write a 2d array to a csv file with delimiter

Use csv module by import csv also take a note you might need either writerow() or writerows().

What's the difference you may ask?

writerow takes an iterable of cells to write:

writerow([1,2,2])
->
1,2,2

writerows takes an iterable of iterables of cells to write:

writerows([[1,2,3],
[4,5,6],
[6,7,8]])
->
1,2,3
4,5,6
6,7,8

Which can be ofcourse be given as a variable. Like

a = [[1,2,3],[4,5,6],[6,7,8]]
writerows(a)

Conclusion writerow takes 1-dimensional data (one row), and writerows takes 2-dimensional data (multiple rows).

Program for you:

import csv

a = [[1,2,3,4],[5,6,7,8]]

with open("new_file.csv","w+") as my_csv:
csvWriter = csv.writer(my_csv,delimiter=',')
csvWriter.writerows(a)

Note open() takes two arguments here the file to be written and the mode.

What is a mode you may ask?

It specifies how the file should be opened. In my case w+ means open file my_file.csv if it exists if it doesn't then fine create a new one and write.

There are several modes choose one. Note: w+ overwrites everytime you use it. That is old data in file will be overwritten so if you want to just append use a. Take a look at this for more details on modes.File modes

Best way to save a CSV file of a 2 dimensional array or list in Python?

If testarray contains multiple rows. Use writerows instead of writerow

import csv

testarray = [["a", "b"], ["c", "d"]]

with open('test.csv', mode='w') as employee_file:
employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"',
quoting=csv.QUOTE_MINIMAL)
employee_writer.writerows(testarray)

Converting CSV File Into 2D Array

I would just add the split result (String[]) to a List then if you really want it as a 2d array then convert it after the fact.

List<String[]> lines = new ArrayList<String[]>();
while ((thisLine = myInput.readLine()) != null) {
lines.add(thisLine.split(";"));
}

// convert our list to a String array.
String[][] array = new String[lines.size()][0];
lines.toArray(array);

read .csv file into 2D-array

You don't need 2 loops in while loop, here is the solution.

public class array2D
{
private static int[][] readArrayFromFile(String filename)
{
int[][] array = new int[9][9];
try
{
Scanner myFileReader = new Scanner(new File(filename));

int i = 0;
while (myFileReader.hasNextLine())
{

String line = myFileReader.nextLine();
String[] tokens = line.split(";");

for (int j = 0; j < tokens.length; j++)
{
array[i][j] = Integer.parseInt(tokens[j]);
}
i++;
}
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
}
return array;
}

private static void printArray(int[][] inputArray)
{
for (int y = 0; y < inputArray.length; y++)
{
for (int x = 0; x < inputArray[y].length; x++)
{
System.out.print(inputArray[y][x] + "\t");
}
System.out.println();
}
System.out.println();
}

public static void main(String[] args)
{
String filename = "./src/test.csv";
int[][] sudokuField = readArrayFromFile(filename);
printArray(sudokuField);
}
}

Write a 2D array to a CSV file in python

You need to transpose your array first

import numpy as np
arr = np.array([[0.0, 1.0, 2.0, 3.0],[5.0, 1.0, 3.0, 3.0],[1.0, 1.0, 3.0, 3.0 ]])
arr_t = arr.T
print(arr_t)

output

[[0. 5. 1.]
[1. 1. 1.]
[2. 3. 3.]
[3. 3. 3.]]

Then follows as earlier.

How to create a 2d array from a CSV file

You should initialize child array of 2d array:

foreach(string sFileline in sFileLines)
{
string[] rowarray = sFileline.Split(",".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);

smartdata[i]=new string[rowarray.Length];
for (int j = 0; j < rowarray.Length; j++)
{

smartdata[i][j] =rowarray[j]; //where the error occurs
//Debug.Log(smartdata[i][j]);

}
i = i + 1 ;
}


Related Topics



Leave a reply



Submit