How to combine a numpy array and a text column and export to csv

前端 未结 1 397
星月不相逢
星月不相逢 2021-01-06 19:10

I want to combine a numpy array and a column which i a string as an identifier for export to a csv file which i can then import into excel.

For example:

<         


        
1条回答
  •  借酒劲吻你
    2021-01-06 19:27

    import numpy as np
    
    a = np.random.rand(6,4)
    b = ['test']*6
    
    c = np.column_stack([a,b])
    np.savetxt('/tmp/out', c, delimiter=',', fmt='%s')
    

    writes something like

    0.70503807191,0.19298150889,0.962915679186,0.655430709887,test
    0.586655200042,0.379720344068,0.136924270418,0.547277504174,test
    0.777238053817,0.642467338742,0.709351872598,0.932239808362,test
    0.386983024375,0.753005132745,0.124107902275,0.472997270033,test
    0.169711196953,0.735713880779,0.280588048467,0.726851876957,test
    0.20578446385,0.379406838045,0.640154333103,0.579077700263,test
    

    to /tmp/out.


    Following up on Paul's suggestion, if you have pandas, you could form a DataFrame quite easily and then call its to_csv method:

    import numpy as np
    import pandas as pd
    
    a = np.random.rand(6,4)
    b = np.asarray(['test']*6)
    
    df = pd.DataFrame(a)
    df['b'] = b
    
    df.to_csv('/tmp/out')
    

    0 讨论(0)
提交回复
热议问题