pandas 和 numpy 中 where 使用

注意: df1.where(cond,df2) 等价于 np.where(cond, df1, df2)

1. pandas.DataFrame.where

DataFrame.where(cond, other=nan, inplace=False, axis=None, level=None, try_cast=False, raise_on_error=True)
功能:按条件查找替换,cond 为 True 则 self 值保持不变;False 改为参数 other 对应的值。结果返回与 self 相同的对象。
参数:
cond 查找条件
other cond为False时要替换的值
inplace 是否在原数据上操作

>>> import numpy as np
>>> import pandas as pd
>>> data = pd.DataFrame(np.arange(12).reshape(3,4),columns=['a','b','c','d'])
>>> data
   a  b   c   d
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
>>> data.where(data['a']>3, 3.0)
   a  b   c   d
0  3  3   3   3
1  4  5   6   7
2  8  9  10  11

2.numpy.where

声明: 首先强调一下,where()函数对于不同的输入,返回值是不同的。

  1. 当数组是一维数组时,返回的值是一维的索引,所以只有一组索引数组

  2. 当数组是多维数组时,满足条件的数组值返回的是值的位置索引,因此会有两组索引数组来表示值的位置。

>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.where(a>5)
(array([6, 7, 8, 9], dtype=int64),)

>>> b = np.arange(20).reshape(4,5)
>>> b
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
>>> np.where(b>10)
(array([2, 2, 2, 2, 3, 3, 3, 3, 3], dtype=int64), array([1, 2, 3, 4, 0, 1, 2, 3, 4], dtype=int64))

具体实现

numpy.where(condition[, x, y])
功能:
参数:
condition: 判定条件,如果True,选择 x;False,选择y(数据类型为数组,bool 值)x,y(可选): x 和 y 的 shape 必须和 condition 相同(可以采用 broadcast,广播机制)
①如果参数有condition,x和y,它们三个参数的shape是相同的。那么,当condition中的值是true时返回x对应位置的值,false是返回y的。
②如果参数只有condition的话,返回值是condition中元素值为true的位置索引,且是以元组形式返回,元组的元素是ndarray数组,表示位置的索引

>>> np.where([[True, False], [True, True]],	# 官网例子
...          [[1, 2], [3, 4]],
...          [[9, 8], [7, 6]])
array([[1, 8],
       [3, 4]])
       
 >>> x = np.arange(9).reshape(3, 3)
>>> np.where(x>5)		# ndarray 数组分别表示对应的 行和列
(array([2, 2, 2], dtype=int64), array([0, 1, 2], dtype=int64))

https://www.cnblogs.com/zz22–/p/8654395.html

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PandasNumpy 提供了很多方便的函数方法,可以用来清理和处理数据。下面是一些常用的清理数据的方法: 1. 处理空值 使用 Pandas 的 `dropna()` 方法可以删除包含空值的行或列,使用 `fillna()` 方法可以用指定的值来填充空值。例如: ```python import pandas as pd import numpy as np # 创建一个包含空值的 DataFrame df = pd.DataFrame({'A': [1, 2, np.nan, 4], 'B': [5, np.nan, 7, 8], 'C': [9, 10, 11, 12]}) # 删除包含空值的行 df = df.dropna() # 用指定的值填充空值 df = df.fillna(0) ``` 2. 处理重复值 使用 Pandas 的 `drop_duplicates()` 方法可以删除重复的行,例如: ```python import pandas as pd # 创建一个包含重复行的 DataFrame df = pd.DataFrame({'A': [1, 2, 2, 4], 'B': [5, 6, 7, 8], 'C': [9, 10, 10, 12]}) # 删除重复的行 df = df.drop_duplicates() ``` 3. 处理异常值 使用 Numpy 的 `where()` 方法可以找到符合条件的数据,并将其替换为指定的值。例如: ```python import numpy as np # 创建一个包含异常值的数组 arr = np.array([1, 2, 3, -999, 4, 5, -999, 6]) # 将异常值替换为指定的值 arr = np.where(arr == -999, np.nan, arr) ``` 4. 处理字符串 使用 Pandas 的 `str` 属性可以对字符串进行处理,例如: ```python import pandas as pd # 创建一个包含字符串的 Series s = pd.Series(['hello', 'world', 'Python']) # 将字符串转换为大写 s = s.str.upper() # 查找包含指定子串的字符串 s = s[s.str.contains('O')] ``` 以上是一些常用的清理数据的方法,具体的方法还需要根据你的具体需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值