I have a List of List of int called NN which i would like to write to a csv file like this:
List<List<int>> NN = new List<List<int>>();
The NN list:
1,2,3,4,5,6
2,5,6,3,1,0
0,9,2,6,7,8
And the output csv file should look like this:
1,2,0
2,5,9
3,6,2
4,3,6
5,1,7
6,0,8
What is the best way to achieve that?
If there is a better representation you would recommend instead of the nested list i'll be glad to know.
(The purpose is that each list of int is the weights between the last and next layer in the neural network).
The most common method to write data from a list to CSV file is the writerow() method of writer and DictWriter class. Example 1: Creating a CSV file and writing data row-wise into it using writer class.
CSV: Import the csv module in Python, create a csv writer object, and write the list of lists to the file in using the writerows() method on the writer object. What is this? Pandas: Import the pandas library, create a Pandas DataFrame, and write the DataFrame to a file using the DataFrame method DataFrame.
DictWriter() class can be used to write to a CSV file from a Python dictionary. Here, file - CSV file where we want to write to. fieldnames - a list object which should contain the column headers specifying the order in which data should be written in the CSV file.
Here is how you can do it:
List<List<int>> NN = new List <List<int>>
{
new List<int> {1,2,3,4,5,6},
new List<int> {2,5,6,3,1,0},
new List<int> {0,9,2,6,7,8}
};
//Get expected number of rows
var numberOfRows = NN[0].Count;
var rows =
Enumerable.Range(0, numberOfRows) //For each row
.Select(row => NN.Select(list => list[row]).ToList()) //Get row data from all columns
.ToList();
StringBuilder sb = new StringBuilder();
foreach (var row in rows)
{
sb.AppendLine(string.Join(",", row));
}
var result = sb.ToString();
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