combine two text separated by one series in python

Viewed 70

I'm trying to combine odd columns' text and even columns' text.

sample series

   column
0   a
1   b
2   c
3   d

and 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?

3 Answers

You can do this by reshapeing the underlying numpy array, construct a new df from this and then apply a str join:

In[14]:
pd.DataFrame(df['column'].values.reshape((2,-1))).apply(''.join, axis=1)

Out[14]: 
0    ab
1    cd
dtype: object

Slightly more obscure is after reshaping is to sum row-wise which will concatenate the strings:

In[15]:
pd.DataFrame(df['column'].values.reshape((2,-1))).sum(axis=1)

Out[15]: 
0    ab
1    cd
dtype: object

This happens because you concatenate them on indices, which do not match. You either need to reset indices, or use underlying numpy arrays.

>>> df['column'][::2].values + df['column'][1::2].values

array(['ab', 'cd'], dtype=object)

>>> df['column'][::2].reset_index(drop=True) + df['column'][1::2].reset_index(drop=True)
0    ab
1    cd
Name: column, dtype: object

You can do this using values of column as an array and concat on even and odd indices as:

a = df.column.values
pd.DataFrame(a[::2]+a[1::2],columns=['column'])

    column
0   ab
1   cd
Related