Python 如何基于以前的列有条件地设置空列值

Python 如何基于以前的列有条件地设置空列值,python,pandas,Python,Pandas,我想按如下方式插入第3列的值: A+ if col 1 is a and col 2 is positive A- if col 1 is a and col 2 is negative B+ if col 1 is B and col 2 is positive B- if col 1 is B and col 2 is negative 数据: 因此,我希望得到的df为: COL1 COL2 COL3 0 a -2 A- 1 a 4

我想按如下方式插入第3列的值:

A+ if col 1 is a and col 2 is positive
A- if col 1 is a and col 2 is negative
B+ if col 1 is B and col 2 is positive
B- if col 1 is B and col 2 is negative
数据:

因此,我希望得到的df为:

     COL1  COL2  COL3
0     a    -2      A-
1     a     4      A+
2     b     10     B+
3     b     -8     B-
4     a     10     A+
5     b     5      B+

几乎是
np的dup。其中
,正如anky_91所注意到的:

df['COL3'] = df.COL1.str.upper() + np.where(df.COL2.gt(0),'+', '-')
给出了预期的输出:

  COL1  COL2 COL3
0    a    -2   A-
1    a     4   A+
2    b    10   B+
3    b    -8   B-
4    a    10   A+
5    b     5   B+

这抓住了
0
表示无符号符号的机会

df.COL1.str.upper() + np.sign(df.COL2).map(['', '+', '-'].__getitem__)

0    A-
1    A+
2    B+
3    B-
4    A+
5    B+
dtype: object
df.COL1.str.upper() + np.sign(df.COL2).map(['', '+', '-'].__getitem__)

0    A-
1    A+
2    B+
3    B-
4    A+
5    B+
dtype: object