Change an array of arrays in an array of strings with pandas

We have this problem, this array of arrays:

m2 = pd.DataFrame([
    [[14,38,51,65,84,85]],
    [[3,34,58,65,66,75]],
    [[3,15,68,70,80,82]],
    [[19,31,42,50,54,97]],
    [[4,9,48,62,74,77]],
])

must become this array of strings:

0    14, 38, 51, 65, 84, 85
1     3, 34, 58, 65, 66, 75
2     3, 15, 68, 70, 80, 82
3    19, 31, 42, 50, 54, 97
4      4, 9, 48, 62, 74, 77

The solution

The solution starts from considering that you can

  • transform a list (or array) in a string that contains the sqare brackets at start and end
  • get rid of the square brackets with [1:-1] that will eliminate the first and last character of the string being the square parentesys
# example
a = [1,2,3]
b = [str(x) for x in a]

>>> b
'[1,2,3,4']

Now to get rid of the []:

b = b[1:-1]

>>> b
'1,2,3,4'

Now we apply this to the dataframe:

import pandas as pd

#m2 = pd.read_csv('newm2.csv', sep=',s', header=None)

m2 = pd.DataFrame([
    [[14,38,51,65,84,85]],
    [[3,34,58,65,66,75]],
    [[3,15,68,70,80,82]],
    [[19,31,42,50,54,97]],
    [[4,9,48,62,74,77]],
])

m2[0] = m2[0].apply(lambda x: str(x)[1:-1])

print(m2[0])

output:

0    14, 38, 51, 65, 84, 85
1     3, 34, 58, 65, 66, 75
2     3, 15, 68, 70, 80, 82
3    19, 31, 42, 50, 54, 97
4      4, 9, 48, 62, 74, 77


Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.