Combines two texts separated by a series in Python… here is a solution to the problem.
Combines two texts separated by a series in Python
I’m trying to combine text for odd columns and text for even columns.
Sample series
column
0 a
1 b
2 c
3 d
I want this output
column
0 ab
1 cd
I tried
new_df['new'] = df['column'][::2].map(str) + df['column'][1::2]
But it returns
new
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
Can anyone help me?
Solution
You can do this by reshaping
the underlying numpy
array, constructing a new df from it, and then applying
a str to join
:
In[14]:
pd. DataFrame(df['column'].values.reshape((2,-1))).apply(''.join, axis=1)
Out[14]:
0 ab
1 cd
dtype: object
To be slightly more obscure, reshape is followed by line sum
, which concatenates the string:
In[15]:
pd. DataFrame(df['column'].values.reshape((2,-1))).sum(axis=1)
Out[15]:
0 ab
1 cd
dtype: object