Convert numbers to string to array in python

I have. Csv file and it looks like

 1, 1 2 3 4 5
 3, 2 3 4 5 6
 2, 5 6 5 4 8
 5, 5 4 8 6 2
 ... 

how can i do to get the first column

a = [1 3 2 5 ...] 

and matrix

b = [ 1 2 3 4 5
      2 3 4 5 6
      5 6 5 4 8
      5 4 8 6 2 ]

with numer numer array and i tried

data = np.asarray(pd.read_csv('Data.csv'))

but it’s even worse ...

+4
source share
3 answers

I think you need

df=pd.read_csv()
first_col=np.array(df.iloc[:0])
df_array=np.array(df.iloc[:,1:])
+2
source

pandasIt supports multiple delimiters through a regular expression pd.read_csv, engine='python'. You can try something like this:

df = pd.read_csv('Data.csv', header=None, sep=' |, ',
                 engine='python', dtype=int)

Then extract your data as follows:

a = df.iloc[:, 0].values
b = df.iloc[:, 1:].values
+1
source

Numpy np.loadtext() , :

In [70]: col1, col2 = np.loadtxt('test.csv', converters={0:int, 1:bytes.decode}, dtype=str, delimiter=',', unpack=True)

In [71]: col1 = col1.astype(int)

In [72]: col2 = np.vstack(np.core.defchararray.split(col2)).astype(int)

:

In [73]: col1
Out[73]: array([1, 3, 2, 5])

In [74]: col2
Out[74]: 
array([[1, 2, 3, 4, 5],
       [2, 3, 4, 5, 6],
       [5, 6, 5, 4, 8],
       [5, 4, 8, 6, 2]])

, col2 to , :

In [76]: col2
Out[76]: 
array([' 1 2 3 4 5', ' 2 3 4 5 6', ' 5 6 5 4 8', ' 5 4 8 6 2'], 
      dtype='<U10')

, , vstack() astype(). :

In [77]: np.core.defchararray.split(col2)
Out[77]: 
array([['1', '2', '3', '4', '5'], ['2', '3', '4', '5', '6'],
       ['5', '6', '5', '4', '8'], ['5', '4', '8', '6', '2']], dtype=object)
+1

Source: https://habr.com/ru/post/1693148/


All Articles