0

I have a vector, it is np.array([[1,2,3]]).

I want to save the vector and the name of the vector in the same row.

For example

Vector1 1 2 3

Vector2 4 5 6

Vector3 7 8 9

Then, I have ever tried like this

import csv
import numpy as np
a=np.array([[1,2,3]])
b='Vector1'
c=[b,a]
with open ('testfile.csv','ab') as fxx:
        w=csv.writer(fxx)
        for row in c:
            w.writerow(row)

the result is enter image description here

then I also have tried this

import csv
import numpy as np
a=np.array([[1,2,3]])
b='Vector1'
c=np.append(b,a)
with open ('testfile3.csv','ab') as fxx:
        w=csv.writer(fxx)
        for row in c:
            w.writerow(row)

And then the result is enter image description here

But the result what I want is enter image description here

3 Answers 3

1
import csv
import numpy as np
a=np.array([[1,2,3]])
b='Vector1'
c=np.append(b,a)
print(c)
with open ('testfile3.csv','a') as fxx:
        w=csv.writer(fxx)
        w.writerow(c)
Sign up to request clarification or add additional context in comments.

Comments

0

writerow() expects a sequence where each element will fill a column, ie

`writer.writerow(["foo", 42, "bar")

will result in (quoting and delimiter depending on your writer params):

"foo",42,"bar"

In your code you create a list c as:

c=['Vector1', [[1, 2, 3]]]

ie your first element is a string and the second a list of one element which is another list.

then iterate over this list to pass each of it's elements to your writer, so basically what you're doing is:

writer.writerow("Vector1")
writer.writerow([[1, 2, 3]])

For the first line, since strings are sequences, it will fill one column per character resulting in (quoting and delim depending on your writer config) :

"V","e","c","t","o","r","1"

and for the second, since you pass a list of one element, it will fill one single column with the string representation of the single element in the list:

"[1, 2, 3]"

If what you want is

"Vector1",1,2,3

then the obvious solution is to pass the correct sequence to writerow:

writer.writerow(["Vector1", 1, 2, 3])

Now you just have to change your code to correctly produce this sequence...

Comments

0
import pandas as pd
a = [[1, 2, 3]]
b = 'Vector1'
a[0].append(b)
print(a)
df = pd.DataFrame(a)
print(df)
df.to_csv('data.csv')

output:

 0  1  2        3
0  1  2  3  Vector1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.