Pandas DataFrame列连接

Nec*_*ard 7 python merge numpy concatenation pandas

我有一个pandas Dataframe y,有100万行和5列.

np.shape(y)  
(1037889, 5)
Run Code Online (Sandbox Code Playgroud)

列值都是0或1.看起来像这样:

y.head()  
a, b, c, d, e  
0, 0, 1, 0, 0  
1, 0, 0, 1, 1  
0, 1, 1, 1, 1  
0, 0, 0, 0, 0
Run Code Online (Sandbox Code Playgroud)

我想要一个包含100万行和1列的Dataframe.

np.shape(y)  
(1037889, )
Run Code Online (Sandbox Code Playgroud)

列只是连接在一起的5列.

New column  
0, 0, 1, 0, 0  
1, 0, 0, 1, 1  
0, 1, 1, 1, 1  
0, 0, 0, 0, 0
Run Code Online (Sandbox Code Playgroud)

我一直在尝试不同的事物一样merge,concat,dstack,等...但似乎无法弄清楚这一点.

Rom*_*kar 11

如果您希望新列将所有数据连接到字符串,那么apply()函数就是好的情况:

>>> df = pd.DataFrame({'a':[0,1,0,0], 'b':[0,0,1,0], 'c':[1,0,1,0], 'd':[0,1,1,0], 'c':[0,1,1,0]})
>>> df
   a  b  c  d
0  0  0  0  0
1  1  0  1  1
2  0  1  1  1
3  0  0  0  0
>>> df2 = df.apply(lambda row: ','.join(map(str, row)), axis=1)
>>> df2
0    0,0,0,0
1    1,0,1,1
2    0,1,1,1
3    0,0,0,0
Run Code Online (Sandbox Code Playgroud)