您可以使用numpy.where()函数来根据条件在DataFrame中创建新的列。

以下是实现您要求的代码示例:

import pandas as pd
import numpy as np

# 创建示例DataFrame
df = pd.DataFrame({'a': [1, 2, 3, 4, 5], 'b': [0, 0, 0, 0, 0], 'c': [1, 2, 3, 4, 5], 'd': [5, 4, 3, 2, 1]})

# 根据条件更新b字段的值
df['b'] = np.where(df['a'] == 3, 0, np.where(df['c'] > df['d'], 1, 0))

print(df)

输出结果为:

   a  b  c  d
0  1  0  1  5
1  2  0  2  4
2  3  0  3  3
3  4  1  4  2
4  5  1  5  1

在这个示例中,通过嵌套使用np.where()函数来实现多个条件判断,根据不同的条件更新b字段的值。如果a字段等于3,则b字段的值为0;否则,如果c字段大于d字段,则b字段的值为1;否则,b字段的值为0

dataframe中当a字段等于3则b字段值为0否则当c 字段大于d字段则b字段值为1否则为0

原文地址: https://www.cveoy.top/t/topic/imBP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录