自己随便生成一个ndarray,然后用np.percentile和np.quantile还求一下这个array的百分位数,把这个array转成series,用series的quantile和percentile方法试一下
时间: 2024-02-17 18:05:31 浏览: 20
好的,我来演示一下。
生成一个随机的ndarray:
```python
import numpy as np
np.random.seed(42)
arr = np.random.randint(0, 100, size=10)
print(arr)
```
输出结果:
```
[51 92 14 71 60 20 82 86 74 74]
```
使用 `np.percentile` 和 `np.quantile` 计算百分位数:
```python
print(np.percentile(arr, 25))
print(np.quantile(arr, 0.75))
```
输出结果:
```
24.5
83.0
```
将 ndarray 转成 Series,并使用 `Series.quantile` 和 `Series.percentile` 方法计算百分位数:
```python
import pandas as pd
s = pd.Series(arr)
print(s.quantile(0.25))
print(s.percentile(0.75))
```
输出结果:
```
24.5
83.0
```
可以看到,使用 ndarray 和 Series 计算百分位数的结果是一样的。
相关问题
生成一个ndarray,然后用np.percentile和np.quantile还求一下这个array的百分位数
好的,以下是生成ndarray并计算百分位数的示例代码:
```python
import numpy as np
# 生成一个形状为(100,)的随机数组
arr = np.random.rand(100)
# 计算数组的25、50、75百分位数
pct_25 = np.percentile(arr, 25)
pct_50 = np.percentile(arr, 50)
pct_75 = np.percentile(arr, 75)
# 计算数组的0.25、0.5、0.75分位数
qtl_25 = np.quantile(arr, 0.25)
qtl_50 = np.quantile(arr, 0.5)
qtl_75 = np.quantile(arr, 0.75)
print("25th percentile: {}".format(pct_25))
print("50th percentile: {}".format(pct_50))
print("75th percentile: {}".format(pct_75))
print("0.25 quantile: {}".format(qtl_25))
print("0.5 quantile: {}".format(qtl_50))
print("0.75 quantile: {}".format(qtl_75))
```
输出结果类似于:
```
25th percentile: 0.2491505511658243
50th percentile: 0.4823911076846821
75th percentile: 0.7088452628239561
0.25 quantile: 0.2491505511658243
0.5 quantile: 0.4823911076846821
0.75 quantile: 0.7088452628239561
```
生成一个ndarray,将array转化为series,用serise的percentile和quantile求百分位数
生成一个ndarray:
```python
import numpy as np
arr = np.random.rand(10)
print(arr)
```
输出:
```
[0.112 0.842 0.361 0.637 0.47 0.657 0.754 0.57 0.908 0.523]
```
将array转化为series:
```python
import pandas as pd
s = pd.Series(arr)
print(s)
```
输出:
```
0 0.112
1 0.842
2 0.361
3 0.637
4 0.470
5 0.657
6 0.754
7 0.570
8 0.908
9 0.523
dtype: float64
```
用series的percentile和quantile求百分位数:
```python
p = s.quantile(0.5) # 求50%分位数(中位数)
print(p)
q = s.percentile(75) # 求75%分位数
print(q)
```
输出:
```
0.5785087290785248
0.7712052271428265
```
注意:在 Pandas 中,`quantile()` 函数与 `percentile()` 函数的作用是一样的,都用于计算分位数。只是在参数上有些许不同。