Antonio López Ruiz Antonio López Ruiz - 1 year ago 57
Python Question

Converting rows of dataframes into matrices - Python Pandas

I have the following dataframe:

Pclass Sex Fare Embarked Title Family
3 0 1.0 0 0 1
1 1 2.0 1 3 1
3 1 1.0 1 2 0
1 1 2.0 3 3 1
3 0 2.0 1 1 0


I need to take each row and turn it into a 6X32 matrix.

(Example of 3X10)

3,3,3,3,3,3,3,3,3,3
0,0,0,0,0,0,0,0,0,0
1,1,1,1,1,1,1,1,1,1


I need that but for every element of the column and 32 times instead of 10.

My code:

from itertools import repeat
array = []
for i in range(0,len(datos)):
rows = datos.iloc[i,:]
for j in range(0,len(rows)):
array.append([rows[j]]*10)


I'm not sure how to do it to separate each row into a unique array.

Answer Source

Everything at once

np.dstack([df.values.astype(int)] * 32)

You can even turn it into a series with matching index

pd.Series(np.dstack([df.values.astype(int)] * 32).tolist(), df.index).apply(np.array)

0    [[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,...
1    [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,...
2    [[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,...
3    [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,...
4    [[3, 3, 3, 3, 3, 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download