python - 如何根据先前的列有条件地设置空列值

标签 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

数据:

    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/

相关文章:

python - Pandas :使用枢轴函数进行复杂列转置的更快方法

python - 使用 Flask 连接 MySQL 时出现 500 Internal Server Error

python - 需要列列表,其值在pyspark中大于0

Python 日志文件配置 KeyError : 'formatters'

python - 采样直方图,使样本的总和均匀

python - 如何在 Pandas 中每 2 行执行加权平均?

python - 移动数据框列并更改列顺序

python - 为什么我用 beautifulSoup 刮的时候有 table ,但没有 pandas

python - 在 pandas dataframe 中,如何对选定行执行操作?

python - 如何对 "signal"感兴趣的子进程(无信号)?