Python中如何使用numpy和pandas根据一个数组的值确定另一个数组的值

例如, array1 是一组数字,有正有负, array2 根据 array1 的值,如果是正,就是 True ,否则就是 False 。
应该有一种非常简便的方式实现,不需要 for 循环,请大家赐教,谢谢。
Python中如何使用numpy和pandas根据一个数组的值确定另一个数组的值

5 回复

array2 = map(lambda x: x>0, array1)


import numpy as np
import pandas as pd

# 方法1:使用numpy的where函数
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([10, 20, 30, 40, 50])
condition = arr1 > 2
result = np.where(condition, arr2 * 2, arr2)  # 条件为真时取arr2*2,否则取arr2
print("numpy.where结果:", result)

# 方法2:使用pandas的Series(更灵活)
df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [10, 20, 30, 40, 50]})
df['C'] = np.where(df['A'] > 3, df['B'] * 3, df['B'] * 0.5)
print("\nDataFrame结果:")
print(df)

# 方法3:使用pandas的apply(复杂逻辑)
def custom_logic(row):
    if row['A'] % 2 == 0:
        return row['B'] ** 2
    else:
        return row['B'] ** 0.5

df['D'] = df.apply(custom_logic, axis=1)
print("\napply方法结果:")
print(df)

# 方法4:使用numpy的select(多条件)
conditions = [
    arr1 < 2,
    (arr1 >= 2) & (arr1 <= 4),
    arr1 > 4
]
choices = [arr2 * 0.1, arr2 * 1.5, arr2 * 2.5]
result2 = np.select(conditions, choices)
print("\nnumpy.select结果:", result2)

核心思路:

  • np.where(condition, x, y):满足条件取x,否则取y
  • np.select(conditions, choices):多条件选择
  • pandas的apply()适合复杂业务逻辑
  • 向量化操作比循环快得多

np.where处理简单条件,复杂逻辑用np.selectapply

numpy_array2 = numpy_array1>0

=-=… so easy

In [1]: a = np.array([1,-1,1,-1])

In [2]: b = (a > 0)

In [3]: b
Out[3]: array([ True, False, True, False], dtype=bool)

回到顶部