0

I have a dataframe with four string columns

col1 col2 col3 col4
A.    A.   A.    B. 
A.    A.   A.    A.
A.    A.   B.    B. 

Would like the response like this.

col1 col2 col3 col4 Changed
A.    A.   A.    B.    B
A.    A.   A.    A.    
A.    A.   B.    B.    B
lst = col1,col2,col3,col4
def compare(**kwargs):
  if all(col1 for i in my_list):
     return col1
  elif all(col2 for i in my_list):
     return col2
  elif all(col3 for i in (col3,col4):
     return col3
  elif col4 == col4 :
     return col2
  

df['changed'] = df.apply(lambda x: compare(x), axis = 1)

Bit stuck in getting this right if anyone can help?

6
  • Does it possible to have 'A. A. B. C.' or 'A. A. B. A.'? Commented Sep 16, 2021 at 20:00
  • Yes its possible but very unlikely Commented Sep 16, 2021 at 20:03
  • 2
    For the 2 cases, what is the expected output for Changed column? Commented Sep 16, 2021 at 20:04
  • It would be the latest change Commented Sep 16, 2021 at 20:05
  • 1
    So for the first case 'C' and the second case 'A', right? Commented Sep 16, 2021 at 20:06

2 Answers 2

1

Take the last column if not all values are identical:

df['Changed'] = df['col4'].mask(df.eq(df['col1'], axis=0).all(1), '')

Output:

  col1 col2 col3 col4 Changed
0   A.   A.   A.   B.      B.
1   A.   A.   A.   A.
2   A.   A.   B.   B.      B.
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks @Ben.T, I just realized it ;)
This issue with this it doesn't show NAN when they are the same
@David yes it does, remove the '' in the where.
Hmm thanks but for some reason thats not working
Can you update your question with the exact expected output? How is it not working? Do you use a different dataset?
|
0

Use mask to select row where there are some changes. I slightly modify your dataframe to take into account special cases.

mask = df.ne(df.shift(fill_value=df['col1'], axis=1))
df['Changed'] = df.mask(mask.sum(1) <= 0)[mask].ffill(axis=1)['col4']
>>> df
  col1 col2 col3 col4 Changed
0   A.   A.   A.   B.      B.
1   A.   A.   A.   A.     NaN
2   A.   A.   B.   B.      B.
3   A.   A.   B.   C.      C.
4   A.   A.   B.   A.      A.

1 Comment

@DavidDraper. Can you give it a try to my answer, please? Does it work?

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.