Sai Kumar
Sai Kumar

Reputation: 715

How can I combine two columns in pandas

Is it possible to combine the test1 column values that are not None to test column.

I tried to concatenate but it's not working.

split['new'] = split['test'] + split['test1']

This is what I got. The values such as SSD and HDD got replaced with NaN.

split Dataframe :

       test      test1       new

0      SSD       None        NaN
1     Flash     Storage  FlashStorage
2      SSD       None        NaN
3      SSD       None        NaN
4      SSD       None        NaN
       ...      ......
1298   SSD       None        NaN
1299   SSD       None        NaN
1300  Flash     Storage   FlashStorage
1301   HDD       None        NaN
1302   HDD       None        NaN

I tried but I couldn't able to solve it.

Upvotes: 0

Views: 738

Answers (4)

Pedro Lobito
Pedro Lobito

Reputation: 98881

Late answer, but you can also use:

import numpy as np
split['new'] = "{}{}".format(split['test'], split['test1'].replace(np.nan, '', regex=True))

Upvotes: 1

sundance
sundance

Reputation: 2945

Replace the Nones with empty strings first using fillna:

split["new"] = split["test"].fillna("") + split["test1"].fillna("")

Or if they're actually the string "None":

split["new"] = split["test"].str.replace("None", "") + split["test1"].str.replace("None", "")

Upvotes: 2

BENY
BENY

Reputation: 323226

Try fillna before add them up

split['newcol'] = split.replace('None',np.nan).fillna('')[['test','test1']].sum(1)

Upvotes: 1

Will
Will

Reputation: 1541

You need to use the text accessors, df["column"].str, first and then you've got access to string functions.

Something like:

split['new'] = split['test'].str.cat(split['test1'].str)

Upvotes: 0

Related Questions