1

I have a 2D numpy array of strings. I am trying to save it to a CSV file. So, the issue comes when the sizes of 1D arrays are different.

For Example:

b = [['a','b']    #size of single array = 2
     ['c','d']]   #size of single array = 2

So, now if I try to save it using:

np.savetxt("filename.csv", b, fmt ="%s", delimiter=",")

The output csv file would be:

Col1      Col2     
-------    ----     
a          b        
c          d          

Which is what I want, but now let's say I have a different sized 1D array.

For Example:

b = [['a','b']    #size of single array = 2
     ['c']]       #size of single array = 1

Now, when I try to save it, then the output file is:

Col1      Col2     
-------   ----     
['a'      'b']           
['c']                   

Whereas I want it to be saved as:

Col1       Col2     
-------    ----     
a          b        
c                   

Can someone help me out?

2 Answers 2

1

You can transform it to pandas dataframe first, than save to csv:

import pandas as pd

b = [['a','b'], ['c']]
df = pd.DataFrame(b)
df.fillna('', inplace=True)
df.to_csv(path)

But you asked about numpy array. If you have numpy array of lists, than you can transform it to list of lists first:

import numpy as np
import pandas as pd

b = np.array([['a','b'], ['c']])
b = list(b)
df = pd.DataFrame(b)
df.fillna('', inplace=True)
df.to_csv(path)
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, thanks for the answer. But the converting to list of lists doesn't work. besides the pandas dataframe part, you are doing the same thing as my solution i.e. adjusting the length of the different sized list.
It works. What I meant is that your example isn't correct. You are asking about numpy array, but you are using list of lists in your example. Here you are creating list of lists in your example: b = [['a','b'],['c','d']]
0

Okay, since the issue is with different size of nested lists ( as np.savetxt works for same sized list ). I tried to make the size of all lists the same. And it worked.

I adjusted the length of all different sized 1D lists with the help of Question1 and Question2

If there's any other approach, please answer. It would be very useful

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.