0

I have a pandas DataFrame looking like this:

nameA     statusA     nameB     statusB
a         Q           x         X
b         Q           y         X
c         X           z         Q
d         X           o         Q
e         Q           p         X
f         Q           r         Q

i want to print the rows of this dataframe based on the following rule: output column nameA if statusA is Q else if statusB is Q output column nameB. and in case statusA and statusB are both Q, both columns nameA and nameB should be output.

is there a oneliner for this?

UPDATE:

expected output:

a,Q
b,Q
z,Q
o,Q
e,Q
f,Q,r,Q
3
  • Do you want results from these two conditions to be printed saperately ? Commented May 19, 2015 at 9:42
  • Perhaps it would help to show the output you would like the code to produce? Commented May 19, 2015 at 9:47
  • question updated with expected output Commented May 19, 2015 at 9:50

1 Answer 1

0
> data['con'] = data['statusA'] + data['statusB']
> data.apply(lambda v: v['nameA'] if v['con'] == 'QX' else v['nameB'] if v['con'] == 'XQ' else v['nameA']+ ','+ v['nameB'], axis=1)
0     a
1     b
2     z
3     o
4     e
5    f,r
dtype: object

You can use string concatenation for producing the exact result.

Some thing like

> data.apply(lambda v: v['nameA']+',Q' if v['con'] == 'QX' else v['nameB'] + ',Q' if v['con'] == 'XQ' else v['nameA']+ ',Q,' + v['nameB'] + ',Q', axis=1)
0        a,Q
1        b,Q
2        z,Q
3        o,Q
4        e,Q
5    f,Q,r,Q
dtype: object
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.