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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With