75919


I'm writing a program in Python 3.

What we want to do

[code]

    import numpy as np
    
    # vals a numeric array of size [3,5]
    vals = np.array([.
        [ 1.0, 2.0, 3.0, 4.0, 5.0],
        [ 50.0, 100.0, 150.0, 200.0, 250.0],
        [100.0, 200.0, 300.0, 400.0, 500.0])
    ])
    # String array of size [3] vals
    strs = ['str1','str2','str3',]
    
[/code]

I want to write out the following to a csv file. In other words, I want to
export the data so that there are 3 rows and 6 columns in the csv file.  
csv output Ideal

[code]

    str1, 1.0, 2.0, 3.0, 4.0, 5.0
    str2, 50.0, 100.0, 150.0, 200.0, 250.0
    str3, 100.0, 200.0, 300.0, 400.0, 500.0
    
[/code]

What I've done  
If you only want to write out a numerical array, you can use  
Code 1

[code]

    import csv
    with open('out.csv', 'w') as f:
        writer = csv.writer(f, lineterminator='\n')
        writer.writers(vals)
    
[/code]

However, I cannot insert a string array into this left column.  
The method I just tried is to output the same csv with whatever information is
in the string array at least first, code 1 followed by  
Code 2

[code]

    strs2 = [strs] # Without this, one cell will contain one character.
    with open('out.csv', 'a') as f:
        writer = csv.writer(f, lineterminator='\n')
        writer.writers(strs2)
    
[/code]

but this will only output csv if the  
csv output Current

[code]

    1.0, 2.0, 3.0, 4.0, 5.0
    50.0, 100.0, 150.0, 200.0, 250.0
    100.0, 200.0, 300.0, 400.0, 500.0
    str1, str2, str3 
    
[/code]

The result is as follows.


CC BY-SA 4.0
2021-05-18T07:26:19.270
75917
2021-05-18T08:52:18.427
45372
question
python numpy csv
How to combine string and numeric arrays in Python for csv output


Do this with:

[code]

    strs = ['str1','str2','str3'].
    Do it like this: strs = np.array
    
    strs = np.array([['str1'],['str2'],['str3']])
    csvdata = np.hstack([strs,vals])
    
[/code]

You can use the previous one to write the resulting csvdata to a csv file.


CC BY-SA 4.0
2021-05-18T07:35:25.647
75919
2021-05-18T08:52:18.427
2021-05-18T08:52:18.427
3068
45345
75917
answer