GabyLP GabyLP - 3 months ago 21
Python Question

python- pandas- concatenate columns with a loop

I have a list of columns that I need to concatenate. An example table would be:

import numpy as np
cats1=['T_JW', 'T_BE', 'T_FI', 'T_DE', 'T_AP', 'T_KI', 'T_HE']
data=np.array([random.sample(range(0,2)*7,7)]*3)

df_=pd.DataFrame(data, columns=cats1)


So I need to get the concatenation of each line (if it's possible with a blank space between each value). I tried:

listaFin=['']*1000
for i in cats1:
lista=list(df_[i])
listaFin=zip(listaFin,lista)


But I get a list of tuples:

listaFin:

[((((((('', 0), 0), 1), 0), 1), 0), 1),
((((((('', 0), 0), 1), 0), 1), 0), 1),
((((((('', 0), 0), 1), 0), 1), 0), 1)]


And I need to get something like

[0 0 1 0 1 0 1,
0 0 1 0 1 0 1,
0 0 1 0 1 0 1]


How can I do this only using one loop or less (i don't want to use a double loop)?

Thanks.

Answer

I don't think you can have a list of space delimited integers in Python without them being in a string (I might be wrong). Having said that, the answer I have is:

output = []
for i in range(0,df_.shape[0]):
    output.append(' '.join(str(x) for x in list(df_.loc[i])))
print(output)

output looks like this: ['1 0 0 0 1 0 1', '1 0 0 0 1 0 1', '1 0 0 0 1 0 1']