Py学习  »  Python

如何提取表中的某些值并执行某些操作-python

disukumo • 3 年前 • 1227 次点击  

我有下表(df):

可乐 科尔布
A. Q1
B A2
A. Y2
C L1
B R2

我想打印一个输出,使其基于列值打印,即,如果是A,则应打印“A中的Q1”,如果是B,则应打印“B中存在A2”,如果是C,则“C中存在L1”。到目前为止我试过什么?

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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129030
 
1227 次点击  
文章 [ 1 ]  |  最新文章 3 年前
Andreas
Reply   •   1 楼
Andreas    3 年前

您可以将“应用”与函数一起使用:

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