목록Python (9)
데이터분석 공부하기
1. ~ & isin 활용 : m = m[~m['번호'].isin(target)] 2. .loc 활용 (Row별 selection): oil_18 = oil_18.loc[oil_18['휘발유'] != 0, :] unique_count = oil_18.groupby('번호')[['지역','상표','셀프여부']].nunique() target = unique_count.loc[(unique_count != 1).sum(axis = 1) != 0] #행별로 한 개라도 1이 아니면 True반환, 모두 1이라면 False oil_18.loc[oil_18['번호'].isin(target.index)] -특정 column 내 특정 조건을 추출하고 싶은 경우 3. [] = [] 4. drop 5. List Compre..
1. Datetime 활용: oil_18['기간'] = oil_18['기간'].apply(lambda x: pd.to_datetime(str(int(x)))) def date_split(df): df['year'] = df['datetime'].dt.year df['month'] = df['datetime'].dt.month df['day'] = df['datetime'].dt.day df['week'] = df['datetime'].dt.week 2. 함수 활용(def, apply): def date_year(s): return int(s[:4]) def date_month(s): return int(s[5:7]) def date_day(s): return int(s[8:-1]) car_recall['..
[반복문] 어떤 '조건'이나 '범위' 내에서 어떤 명령을 '반복적'으로 수행 * For문 : -'범위' -> Sequence -Sequence의 원소를 하나씩 변수에 넣어가면서 '원소로 반복'하는 방법 for 변수 in 시퀀스: -반복 시 ' 횟수'만 아는 경우 (for-range) 1) 범위를 아는 경우: range(a,b): a부터 b-1까지 2) 횟수를 아는 경우: range(a): 0부터 a-1까지 -len(): sequence의 원소 수만큼 실행 [LIST] 1) element그대로 받는 경우, for이후 변수(i이던 fruit이던)에 바로 element가 들어간다. fruits = ['apple', 'grape', 'banana'] 1) for fruit in fruits: print(frui..
list comprehension : [출력표현식 for 요소 in 입력 Sequence [if 조건식]] -Python의 네가지 comprehension 기능 중 하나 (list, set, dict, generator) -반복 가능한 iterable 자료형을 생성할 때 사용, 여러 줄의 for/if 조건문도 한 줄로 만들 수 있다 -입력 Sequence로부터 지정된 표현식에 따라 새로운 리스트 컬렉션을 만듬 -문법 : lambda(lambda arguments : expression) : '한 줄'로 함수를 표현하는 익명 함수 기법 f = lambda x, y : x+y f(3,4) map(function, sequence) : input(func, seq)을 each element에 적용하여 lis..
데이터 재구조화(reshaping) 1) pivot() vs pd.pivot_table() vs groupby(): -pivot : 데이터의 형태만 변화; 연산불가 -pivot_table : 형태변화, aggfunc을 통한 연산 가능; 반환값 항상 dataframe) -groupby : 형태변화, 연산가능 (pivot_table보다 빠르고, 컬럼이 series형태면 series로 반환) https://pandas.pydata.org/Pandas_Cheat_Sheet.pdf https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html 2) stack(), unstack() 3) melt() 4) wide_to_long() 5) pd.crosst..
[Matplotlib VS Matlab VS Seaborn] Matplotlib vs. Matlab - Matplotlib : a python visualization library. It is made to work like matlab. - Matlab : numerical computing environment and programming language (best for engineer/scientist) Seaborn : extension to matplotlib(need to be imported together) It introduces additional plot types and visual improvement. [Basics : Figure & Axes] f, ax (figure, a..
★ 문자열 Formatting : 문자열 속 특정 위치에 특정 값 삽입 1) % formatting : %s 문자열, %d 정수, %f 실수 - python3 이에 주로 사용되며 c언어 style - 단점 : 코드가 길어질 수록 장황 my_str = 'My name is %s' % 'harry' my_str 'My name is harry' 2) str.format (a.k.a. '{}'.format())-https://pyformat.info/ - python3 이후부터 사용 -.format() 괄호안에 중괄호에 대입할 문자나 숫자 입력 -{인자 : 자리수.소수점 뒤 자리수 f} : 콜론(:) 전에는 format()에 오는 인자의 인덱스 순서, 콜론(:) 후에 컴마(.)전에는 총 자리수, 컴마(.) 후..
[Multiple Conditions] * Method 1 : np.select() 더보기 numpy.select(condlist, choicelist, default=0) Return an array drawn from elements in choicelist, depending on conditions. -> list를 사용하여 여러 조건을 깔끔하게 걸 수 있다; 스피드가 빠르다. conditions = [(hr['HourlyRate'] = 30) & (hr['HourlyRate'] = 50) & (hr['HourlyRate'] = 70) & (hr['Hourly..
[Function & Using reference] -Builtin Function -Python내 내장함수는 총 69개이다. (https://docs.python.org/3/library/functions.html)-각 함수를 잘 알면 좋을 듯-dir()을 써서 어떤 builtin function이 있는지 알아보기 쉽지 않다.*알아보는 법: python API documentation : https://www.python.org -External Function(어느 함수인지 잘 알아보기) *알아보는 법: 1) dir()로 np, pd를 넣어 그 안에 function list를 볼 수 있다. *반드시 그 함수를 Call해야지만 dir()/help()를 사용할 수 있다. sklearn은 subpackag..