1

I need to add column A to B. I could achive this by doing this:

import pandas as pd

sample_dict = {
               'A' : ["entry", "", "", "entry"],
               'B' : ["foo", "foo", "", ""]
              }
sample_frame = pd.DataFrame(sample_dict)
sample_frame['A'] = sample_frame['A'] + sample_frame['B']
del sample_frame['B']

Then I end up with:

          A
0  entryfoo
1       foo
2          
3     entry

While the two columns are now one, I can hardly distinguish between the two values. What I want is this:

            A
0  entry, foo
1         foo
2          
3       entry

So I want to put a ", " in between the values, but only if one of the values is not "". Otherwise I end up with this if I just use sample_frame['A'] = sample_frame['A'] + ", " + sample_frame['B']:

            A
0  entry, foo
1       , foo
2           ,      
3      entry, 

So, how can I achive this conditional addition?

1 Answer 1

2

Even your solution is fine, just strip off the leftovers at last, using Series.str.strip:

sample_frame['A'] = (sample_frame['A'] + ", " + sample_frame['B']).str.strip(', ')

OUTPUT:

            A
0  entry, foo
1         foo
2            
3       entry
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.