如何在 table 中提取某些值并执行某些操作 - python

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

我有以下 table (df):

ColA ColB
一个 Q1
B A2
一个 Y2
C L1
B R2

我想打印一个输出,使其根据列值打印,即,如果是 A,则应打印 'Q1 in A',如果是 B,则应打印 'A2 is present in B',如果是C则'L1 exists in C'。到目前为止我尝试了什么?

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')

但是我收到以下错误:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().我该如何解决?

期望的输出:

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

您可以将 apply 与函数一起使用:

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