How to concatenate all (string) values in a given pandas dataframe row to one string?
IIUC, by using apply
, join
df.apply(lambda x :' '.join(x.astype(str)),1)
Out[348]:
0 I want to join strings
1 But only in row 1
dtype: object
Then you can assign them
df1=df.iloc[1:]
df1['5']=df.apply(lambda x :' '.join(x.astype(str)),1)[0]
df1
Out[361]:
0 1 2 3 4 5
1 But only in row 1 I want to join strings
For Timing :
%timeit df.apply(lambda x : x.str.cat(),1)
1 loop, best of 3: 759 ms per loop
%timeit df.apply(lambda x : ''.join(x),1)
1 loop, best of 3: 376 ms per loop
df.shape
Out[381]: (3000, 2000)
Use str.cat
to join the first row, and assign to the second.
i = df.iloc[1:].copy() # the copy is needed to prevent chained assignment
i[df.shape[1]] = df.iloc[0].str.cat(sep=' ')
i
0 1 2 3 4 5
1 But only in row 1 I want to join strings