Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combine two text separated by one series in python

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?

like image 844
Baekse Avatar asked Nov 20 '25 08:11

Baekse


2 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
like image 63
EdChum Avatar answered Nov 21 '25 21:11

EdChum


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
like image 23
hellpanderr Avatar answered Nov 21 '25 22:11

hellpanderr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!