要比较两个Pandas列并将其设置为标签,可以使用np.where()
函数。以下是一个示例代码:
import pandas as pd
import numpy as np
# 创建示例数据
data = {'A': [1, 2, 3, 4, 5],
'B': [2, 4, 6, 8, 10]}
df = pd.DataFrame(data)
# 使用np.where()函数比较两列并设置为标签
df['Label'] = np.where(df['A'] > df['B'], 'A>B', np.where(df['A'] < df['B'], 'A
输出结果如下:
A B Label
0 1 2 A
在上面的示例中,我们创建了一个包含两列(A和B)的DataFrame。然后,我们使用np.where()
函数比较列A和列B的值,并根据比较结果设置标签。如果A大于B,则标签为'A>B';如果A小于B,则标签为'A