티스토리 뷰
구간나누기¶
- np.arange() # a부터 b까지 c단위로 나눈다.
- np.linspace() # 구간을 나눈다. ex 히스토그램
- np.bincount() # 구간을 나눠서 개수를 셈 ex) 140~150은 1명 150~160은 3명 160~170은 5명 170~180은 7명 180~190은 4명
- np.digitize() # 구간을 나눠서 mapping 시킴 ex) 143, 142는 0, 152, 155, 156은 1, ....
- np.histogram() => plt.hist()
In [12]:
import numpy as np
import matplotlib.pyplot as plt
In [15]:
np.arange(-1,1,0.1) # 1 대신 1과 1.1 사이의 어떤 값을 집어넣으면 1도 포함시킬수 있다.(20개에서 21개가 된다.)
Out[15]:
In [17]:
np.linspace(-1,1,21) # arange와는 다르게 개수를 준다. (끝점이 포함되므로 1도 들어감)
Out[17]:
In [20]:
x = np.linspace(-1,1,101)
y = x**3
plt.plot(x,y)
plt.xlabel('x')
plt.ylabel('y')
Out[20]:
bincount()¶
- 정수가 나타난 횟수를 센다
In [22]:
a = np.random.randint(10,size=100)
a
Out[22]:
In [28]:
np.bincount(a) # 0 13개, 1 5개, 2 9개, 3 9개, 4 15개, .....
Out[28]:
In [29]:
plt.plot(np.bincount(a))
#plt.ylm(0,16) y의 범위를 0부터 16으로 한다.
Out[29]:
In [113]:
a = np.random.randint(5,10,size=100)
a
Out[113]:
In [27]:
np.bincount([7,5,5,6,7]) # 5 2개, 6 1개, 7 2개, 항상 0인 값부터 갯수를 출력한다.
Out[27]:
histogram()¶
- 설정한 구간에서의 항목 갯수를 출력한다.
help(np.histogram)
histogram(a, bins=10, range=None, normed=False, weights=None, density=None)
Compute the histogram of a set of data.
Parameters
----------
a : array_like
Input data. The histogram is computed over the flattened array.
bins : int or sequence of scalars or str, optional
If `bins` is an int, it defines the number of equal-width
bins in the given range (10, by default). If `bins` is a
sequence, it defines the bin edges, including the rightmost
edge, allowing for non-uniform bin widths.
In [34]:
a = np.random.rand(100) # 0과 1 사이의 실수
a
Out[34]:
In [35]:
a.min(), a.max()
Out[35]:
In [36]:
plt.hist(a) # 구간(디폴트)값을 10개 줬다.
Out[36]:
In [37]:
np.histogram(a)
Out[37]:
In [45]:
n, b = np.histogram(a, bins=np.arange(0,1,0.1)) # 구간을 9개로 나눴다
n, b
Out[45]:
In [46]:
plt.hist(a, bins=b)
Out[46]:
digitize()¶
- 설정한 구간값을 반환한다.
help(np.digitize)
digitize(x, bins, right=False)
Return the indices of the bins to which each value in input array belongs.
Each index ``i`` returned is such that ``bins[i-1] <= x < bins[i]`` if
`bins` is monotonically increasing, or ``bins[i-1] > x >= bins[i]`` if
`bins` is monotonically decreasing. If values in `x` are beyond the
bounds of `bins`, 0 or ``len(bins)`` is returned as appropriate. If right
is True, then the right bin is closed so that the index ``i`` is such
that ``bins[i-1] < x <= bins[i]`` or ``bins[i-1] >= x > bins[i]`` if `bins`
is monotonically increasing or decreasing, respectively.
Parameters
----------
x : array_like
Input array to be binned. Prior to NumPy 1.10.0, this array had to
be 1-dimensional, but can now have any shape.
bins : array_like
Array of bins. It has to be 1-dimensional and monotonic.
right : bool, optional
Indicating whether the intervals include the right or the left bin
edge. Default behavior is (right==False) indicating that the interval
does not include the right edge. The left bin end is open in this
case, i.e., bins[i-1] <= x < bins[i] is the default behavior for
monotonically increasing bins.
In [53]:
scores=[93, 78, 77, 89, 100, 67, 51, 82, 99, 71] # 93은 4구간, 78은 2구간, 77은 2구간, ... (60이하의 구간, 90이상의 구간이 더 있다.)
d = np.digitize(scores, bins= [60,70,80,90])
d
Out[53]:
In [54]:
grade = ['가', '양', '미', '우', '수']
[grade[i] for i in d]
Out[54]:
연습문제¶
iris 데이터에서 첫번째 칼럼의 값을 구간값으로 바꾸시오. (어떻게 구간을 나누는게 좋을지 고민해보자.)
In [55]:
f = openf = open('iris.csv')
line = f.readline()
features = line.strip().split(',')[:4]
labels = ['Iris-setosa', 'Iris-versicolor', 'Iris-virginica']
data = []
for line in f:
l = line.strip().split(',')
l[:4] = [float(i) for i in l[:4]]
l[4] = labels.index(l[4])
data.append(l)
f.close()
iris = np.array(data)
In [111]:
list(iris[:,0])
r = np.digitize(list(iris[:,0]), bins = [4,5,6,7])
r
Out[111]:
In [61]:
len(d)
Out[61]:
In [71]:
c=np.sort(list(iris[:,0]))
In [73]:
c[49], c[99]
Out[73]:
In [105]:
list(iris[:,0])
d = np.digitize(list(iris[:,0]), bins = [5.4, 6.3])
d
Out[105]:
In [106]:
sum(d==1)
Out[106]:
In [107]:
sum(d==2)
Out[107]:
In [108]:
sum(d==0)
Out[108]:
In [109]:
plt.plot(list(iris[:,0]))
Out[109]:
In [110]:
plt.plot(d)
Out[110]:
In [112]:
plt.plot(r)
Out[112]:
- 풀이
In [115]:
sepal_length = iris[:,0]
sepal_length
Out[115]:
In [116]:
plt.plot(sepal_length)
plt.grid()
In [117]:
plt.hist(sepal_length, bins=100)
pass
In [118]:
t1 = sepal_length[:50]
t2 = sepal_length[50:100]
t3 = sepal_length[100:]
t1.max(), t1.min(), t1.mean()
Out[118]:
In [119]:
t2.max(), t2.min(), t2.mean()
Out[119]:
In [120]:
t3.max(), t3.min(), t3.mean()
Out[120]:
In [121]:
b = [t1.mean(), (t2.mean()+t1.mean())/2, t2.mean(), (t3.mean()+t2.mean())/2, t3.mean()]
In [122]:
s2 = np.digitize(sepal_length, bins=b)
s2
Out[122]:
In [123]:
plt.plot(s2, 'ro')
Out[123]:
'beginner > 파이썬 기초' 카테고리의 다른 글
Matplotlib (0) | 2019.02.19 |
---|---|
NumPy_기타 (0) | 2019.02.19 |
NumPy_정렬 (0) | 2019.02.15 |
NumPy_파일입출력 (0) | 2019.02.14 |
NumPy_함수 (0) | 2019.02.13 |