[英]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. 谢谢。
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). 我不认为你可以在Python中有一个空格分隔的整数列表,而不是它们在一个字符串中(我可能是错的)。 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'] 输出如下所示:['1 0 0 0 1 0 1','1 0 0 0 1 0 1','1 0 0 0 1 0 1']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.