How to extract certain values in a table and do something - python

Viewed 354

I have the following table (df):

ColA ColB
A Q1
B A2
A Y2
C L1
B R2

I would like to print an output such that it prints based on the column values, i.e., if it is A then it should print 'Q1 in A', if it is B then it should print 'A2 is present in B', if it is C then 'L1 exists in C'. What I tried so far?

for i in df:
    if 'A' in df['ColA']:
       print(df['ColB'], 'in A')
    if 'B' in df['ColA']:
       print(df['ColB'], 'is present in B')
    if 'C' in df['ColA']:
       print(df['ColB'], 'exists in C')

But I get the following error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). How do I solve it?

Desired output:

Q1 in A
A2 is present in B
Y2 in A
L1 exists in C
A2 is present in B
1 Answers

You can use apply with a a function:

def prnt(A, B):
    if 'A' in A:
       print(B, 'in A')
    if 'B' in A:
       print(B, 'is present in B')
    if 'C' in A:
       print(B, 'exists in C')

df.apply(lambda row: prnt(row['ColA'], row['ColB']), axis=1)

Q1 in A
Q1 in A
A2 is present in B
A2 is present in B
Y2 in A
Y2 in A
L1 exists in C
L1 exists in C
R2 is present in B
R2 is present in B
Related