Python Dataframe - 获取特定数字与列值之间的最大值

标签 python python-3.x pandas dataframe max

当我的 df 以下时,我想获取一个列“C”,该列在条件“B == 't'”内具有特定值“15”和“A”列之间的最大值

testdf = pd.DataFrame({"A":[20, 16, 7, 3, 8],"B":['t','t','t','t','f']})
testdf

    A   B
0   20  t
1   16  t
2   7   t
3   3   t
4   8   f

我尝试过这个:

testdf.loc[testdf['B']=='t', 'C'] = max(15,(testdf.loc[testdf['B']=='t','A']))

所需的输出是:

    A   B   C
0   20  t   20
1   16  t   16
2   7   t   15
3   3   t   15 
4   8   f   8

你能帮我得到输出吗?谢谢!

最佳答案

np.whereclip一起使用:

testdf['C'] = np.where(testdf['B'].eq('t'), 
                       testdf['A'].clip(15), df['A'])

或者与series.where类似:

testdf['C'] = (testdf['A'].clip(15)
                   .where(testdf['B'].eq('t'), testdf['A'])
              )

输出:

    A  B   C
0  20  t  20
1  16  t  16
2   7  t  15
3   3  t  15
4   8  f   8

关于Python Dataframe - 获取特定数字与列值之间的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66430056/

相关文章:

python - 使用 5 倍交叉验证时,在高度不平衡的数据中混淆 F1 分数 和 AUC 分数

python - FASTAPI 与 Alembic 一起运行,但自动生成不检测模型

python - 带有 BooleanField 的 Flask WTForms FieldList

python - Pandas pivot_table : aggfunc parameter value & quotation marks

python - 在 Pandas 中减去日期时间列时返回错误

python - 用列的值替换 DataFrame 中的空值

python - 开发算法可视化/模拟

python - 如何在水平条形图中绘制计数器对象?

python - 如何创建逻辑来在 pandas 中进行值映射?

python - 创建一个列来保持连续值的运行计数