
주의: 행 렬 == row col == ↓→
fundamental package for scientific computing in Python
ndarraymasked arrays matrices
두 array가 있을 때, 둘이 연산 가능할 때 호환되는 현상
크기가 같을 때 or 둘 중 하나가 1(크기)일때




동일 크기의 두 배열에 있는 각 element의 곱을 구하는 문제
// In C
c = []
for i in range(len(a)):
c.append(a[i] * b[i])
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++) {
c[i][j] = a[i][j] * b[i][j];
}
}
↓
#in numpy
c = a * b
주의: Dot Product가 아닌 같은 크기, 같은 위치 배열 기준
목적이 다른 곳에서 데이터를 가져와 사용하기 위함
arange ones zerosSciPy pandas OpenCVimport numpy as np
a1D = np.array([1, 2, 3, 4])
a2D = np.array([[1, 2], [3, 4]])
a3D = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
numpy.array를 사용할 때에는 dtype을 사용하자(주로 np.int64 사용)
참고: np.int8 : -127~128
u21: 유니코드 21자리

주의: float16과같이 너무 작은 비트수를 float로 표현하면 오차 발생으로 인한 이상한 값이 튀어나올수도..)


공분산 행렬에서 분산 값만 추출하는 경우, 다중회귀분석에서 가중치를 부여할 때 사용
SVD(특이값분해)에서도 사용


np.diag([1, 2, 3], 1)에서 1에 -1값을 넣으면 왼쪽으로도 shift 가능





















loadtxt: 빠진 값이 없는 정형화된 자료, float/int 중심genfromtxt: 값이 빠진 경우, 복잡한 dtype지정, 결측값 처리 등 유연성 높음numpy.save, numpy.load 사용할 때 allow_pickle=False 설정
void는 null로 끝나지 않음을 주의

x[0, 1, 2] == x[0][1][2] x[-1, -1, -1] → 24x[0]x[x % 2 == 0] vectorization
x[[True, False]] vectorization
start:stop:step...은 :의 확장이다
x[:, :, 0] == x[..., 0]
x[:, 0] 는 다르다
x[0, 0, [0, 2]] == x[0, 0, 0:3:2]

x[0, [0, 2], 1]numpy.reshape(a, /, shape = None, order = 'C', newshape = None, copy = None)
# order에서 C는 C언어 기준 (깊은 depth 부터)
# F는 Fortran 기준 (바깥 depth 부터)





ndarray.flatten(order = 'C') #copy 반환
ndarray.flat() #Iterator 반환: 내부적으로 함수가 반환됨 → direct access는 불가, loop만 가능
numpy.ravel(a, order = 'C') #필요할때만 copy해서 반환
축 뒤집기


numpy.transpose(a, axes = None)
numpy.moveaxis(a, source, destination)
numpy.swapaxes(a, axis0, axis1)

numpy.min(a, axis=None, out=None, keepdims= , initial= , where= )
numpy.max(a, axis=None, out=None, keepdims= , initial= , where= )
numpy.sum(a, axis=None, dtype=None, out=None, keepdims= , initial= , where= )
데이터 분석 포커싱

3-Dimension은 Pandas에 존재하지 않음

df['열이름']라 하면 숫자 인덱스가, dfi['열이름']라고 한다면 String 인덱스가 나온다.loc, 인덱스 숫자로 할 땐 ilocclass pandas.Series(data=None, index=None, dtype=None, name=None, copy=None, fastpath=<no_default>
data: array-like, iterable, dict, scalarindex: array-like, index, RangeIndex(default)dtype: str, numpy.dtype, ExtensionDtypename: Hashablecopy: 입력 data의 copy 여부. Series나 1d-ndarray일때만 적용





class pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=None)
data: ndarray, iterable, dict, DataFrameindex: index, array-like, RangeIndex(Default)columns: index, array-like, RangeIndex(Default)dtype: str, numpy.dtype, ExtensionDtypecopy: 입력 data의 copy 여부







하단의 삭제 이후의 연산임


df[start:stop]보다는 df.iloc[start:stop]을 사용함이 맥락적으로 바람직하다.


DataFrame.head(n=5) #[:n]을 반환
DataFrame.tail(n=5) #[-n:]을 반환
DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None, ignore_index=False)
n: int형, 반환할 item의 개수. frac과 같이 쓰지 않음.frac: float형, 전체 대비 반환할 비율. frac > 1일 수 있다. n과 같이 쓰지 않음.replace: bool형, 한 번 이상 같은 행이 sampling 될 수 있는지 설정weights: str, ndarray-like 형. 가중치를 부여한 column 이름random_state: int, array-like, BitGenerator, np.random.RandomState, np.random.Generatoraxis: 0 or index, 1 or columns, Noneignore_index: bool. 반환값의 index 제거 여부DataFrame.describe(percentiles=None, include=None, exclude=None)
percentiles: list-like of numbersinclude: all, list-like of dtypes, Noneexclude: list-like of dtypes, None
https://data.seoul.go.kr/dataList/OA-15182/F/1/datasetView.do







데이터 분석 시 sort는 많이 사용하지 않는다고 한다. 굳이 하려면
DataFrame.sort_values

원시 데이터를 분석 가능하도록 정리하는 과정
DataFrame.astype(dtype, copy=None, errors='raise')
Series.astype(dtype, copy=None, errors='raise')
dtype: str, data type, Series or Mapping or column name → data typecopy: 쓰지 않는 것이 좋음(명시X). copy-on-write로 대체될 예정errors: 'raise', 'ignore'to_datetime, to_numeric, to_timedelta, convert_dtypes 존재
Split - Apply - Combine
pandas documentation
다만 굳이? pandas를 이용하는 것 보다 sql의 join, group by를 사용하는 것이 낫다.

DataFrame.groupby(by=None, axis=<no_default>,
level=None, as_index=True, sort=True, group_keys=True, observed=<no_default>, dropna=True)
by: mapping, function, label, pd.Grouper, listlevel: int, level name, sequence, MultiIndex인 경우 as_index: False인 경우 index가 column에 저장. 기본 index 사용sort: 결과 index sort 여부group_keys: 결과 index의 key 사용 여부. False인 경우 기본 index 사용group 단위로 값이 계산되어 하나의 Scalar 값이 반환



Built-in Aggregation Methods

각 Row에 대해 Group 단위로 Function 적용
In [125]: speeds
Out[125]:
class order max_speed
falcon bird Falconiformes 389.0
parrot bird Psittaciformes 24.0
lion mammal Carnivora 80.2
monkey mammal Primates NaN
leopard mammal Carnivora 58.0
In [126]: grouped = speeds.groupby("class")[["max_speed"]]
In [127]: grouped.transform("cumsum")
Out[127]:
max_speed
falcon 389.0
parrot 413.0
lion 80.2
monkey NaN
leopard 138.2
In [128]: grouped.transform("sum")
Out[128]:
max_speed
falcon 413.0
parrot 413.0
lion 138.2
monkey 138.2
leopard 138.2

Group 전체, 혹은 일부를 제거
In [188]: dff = pd.DataFrame({"A": np.arange(8), "B": list("aabbbbcc")})
In [189]: dff.groupby("B").filter(lambda x: len(x) > 2) #filter을 사용하여 user defined function 적용 가능
Out[189]:
A B
2 2 b
3 3 b
4 4 b
5 5 b

DataFrameGroupBy.apply(func, *args, include_groups=True, **kwargs)
func: callableinclude_groups: func를 group 단위로 적용할지 여부args, kwargs: func에 전달되는 인자들>>> df = pd.DataFrame({'A': 'a a b'.split(),
... 'B': [1, 2, 3],
... 'C': [4, 6, 5]})
>>> df.groupby('A', group_keys=True)[['B', 'C']].apply(lambda x: x / x.sum())
B C
A
a 0 0.333333 0.4
1 0.666667 0.6
b 2 1.000000 1.0
import pandas as pd
df = pd.DataFrame({
"A": ["a", "a", "b"],
"B": [1, 2, 3],
"C": [5, 6, 7]
})
def show_arg(x):
print(x)
return x.sum() # x / x.sum() 으로 바꾸어 보고 결과를 비교해 보자!!
print("include_groups=True")
# include_groups=True (기본값): 그룹 컬럼(A)이 함수에 전달되는 데이터프레임에 포함됨
result1 = df.groupby("A").apply(show_arg)
print(result1)
# include_groups=False: 그룹 컬럼(A)이 함수에 전달되는 데이터프레임에서 제외됨
print("\ninclude_groups=False")
result2 = df.groupby(“A").apply(show_arg, include_groups=False)
print(result2)




https://pandas.pydata.org/pandas-docs/stable/reference/groupby.html