我想插入第 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
数据:
COL1 COL2 COL3
0 a -2
1 a 4
2 b 10
3 b -8
4 a 10
5 b 5
因此我想要一个结果 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+
最佳答案
anky_91 注意到,np.where
几乎是重复的:
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+
关于python - 如何根据先前的列有条件地设置空列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56810040/