'Convert numpy array from space separated to comma separated in python

This is data in .csv format file generally we expect array/ list with [1,2,3,4] comma separated values which it seems that nothing happened in this case

data = pd.read_csv('file.csv')
data_array = data.values

print(data_array)

print(type(data_array[0]))

and here is the output data

[16025788 179 '179batch1640694482' 18055630 8317948789 '2021-12-28'
 8315780000.0 '6214' 'CA' Nan Nan 'Wireless' '2021-12-28 12:32:46'
 '2021-12-28 12:32:46']

<class 'numpy.ndarray'>

So, i am looking for way to find array with comma separated values



Solution 1:[1]

Okay so simply make the changes:

converted_str = numpy.array_str(data_array)
converted_str.replace(' ',',')
print(converted_str)

Now, if you want to get the output in <class 'numpy.ndarray'> simply convert it back to a numpy array. I hope this helps! ?

Solution 2:[2]

Without the csv or dataframe (or at least a sample) there's some ambiguity as to what your data array is like. But let me illustrate things with sample.

In [166]: df = pd.DataFrame([['one',2],['two',3]])

the dataframe display:

In [167]: df
Out[167]: 
     0  1
0  one  2
1  two  3

The array derived from the frame:

In [168]: data = df.values
In [169]: data
Out[169]: 
array([['one', 2],
       ['two', 3]], dtype=object)

In my Ipython session, the display is actually the repr representation of the array. Note the commas, word 'array', and dtype.

In [170]: print(repr(data))
array([['one', 2],
       ['two', 3]], dtype=object)

A print of the array omits those words and commas. That's the str format. Omitting the commas is normal for numpy arrays, and helps distinguish them from lists. But let me stress that this is just the display style.

In [171]: print(data)
[['one' 2]
 ['two' 3]]
In [172]: print(data[0])
['one' 2]

We can convert the array to a list:

In [173]: alist = data.tolist()
In [174]: alist
Out[174]: [['one', 2], ['two', 3]]

Commas are a standard part of list display.

But let me stress, commas or not, is part of the display. Don't confuse that with the underlying distinction between a pandas dataframe, a numpy array, and a Python list.

Solution 3:[3]

Convert to a normal python list first:

print(list(data_array))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 The Myth
Solution 2 hpaulj
Solution 3 run_the_race