1

I have a dataframe :

    c1     c3    c4     c5
r1         this  and
r2  that   str         shld
r3  have         and

The white spaces are chosen to be blank (they were NaN values which I replaced with '' instead)

These strings within the data frame represents error messages, the string only appear when the error is present.

My desired output:

    c1     c3    c4     c5    Error_Message
r1         this  and          this also and
r2  that   str         shld   that also str also shld
r3  have         and          have also and

My current output:

    c1     c3    c4     c5    Error_Message
r1         this  and          also this also and also
r2  that   str         shld   that also str also also shld
r3  have         and          have also also and also

The code I am using:

df_calc['Health_Message'] = df_calc['c1'] + ' also ' + df_calc['c3']  +' also ' \
                                + df_calc['c4'] + ' also ' +  df_calc['c5']

Is there a more pythionic or reliable way to get rid of the unnecessary 'also''s .. there should only be an 'also' between error messages (string values). I am in over my head, thank you

2 Answers 2

1

You can do it like this:

import pandas as pd

x = {"c1":["", "that", "have"], "c3":["this", "str",""],"c4":["and", "", "and"],"c5":["", "shld", ""]}

df = pd.DataFrame.from_dict(x)
df["Error_Message"] = df.apply(lambda row: " also ".join([el for el in row if el]),axis=1)
print(df)

Output:

     c1    c3   c4    c5            Error_Message
0        this  and                  this also and
1  that   str       shld  that also str also shld
2  have        and                  have also and
Sign up to request clarification or add additional context in comments.

3 Comments

@LlewellynHattingh What you mean doesn't change anything? It produce the desired output you wished for?
Hi, my apologies, I had to make some adjustments on my side to the dataframe. Afterwards, your code worked exactly as it should. Thanx so much! I appreciate the simplicity
@LlewellynHattingh don't worry. I'm glad that it worked out.
1

This should help:

>>> a = '1'
>>> b = '2'
>>> c = [a, b]
>>> d = ' also '.join(c)
>>> d
'1 also 2'

In your case - make list of all line contents first - then join.

3 Comments

Thanx, how will I go about making a list of all string values for each row?
pseudo code: c = [] and for each element c.append(element)
it can actually be any collection you can loop over and may be you are already doing it in your code - then just add join part :)

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.