#정리
#05df_sort - 인덱스 / 컬럼명 정렬, 특정 컬럼 기준 값 정렬
#sort_index() : 인덱스와 컬럼에대한 정렬 기능
- ex. order by rownum desc
- 인덱스 기준 - 오름차순 정렬이 기본 값
<인덱스를 기준으로 정렬> - print(df.sort_index()) #인덱스를오름차순
- df.sort_index(axis=0,ascending=True) #인덱스를 오름차순(default)
- print(df.sort_index(axis=0,ascending=False)) #DESC : 인덱스를내림차순
<컬럼명을 기준으로 정렬>
- print(df.sort_index(1)) #컬럼명이오름차순
- print(df.sort_index(axis=1)) #컬럼명이 오름차순
- print(df.sort_index(axis=1,ascending=False)) #컬럼명이 내림차순
#df.sort_values(by=['column name']) : 특정 컬럼 값을 기준으로 정렬- ex. order by salary asc
- print(df.sort_values(by=['salary'])) #salary 기준 오름차순
- print(df.sort_values(by=['salary'],ascending=False)) #salary 기준 내림차순
#df.rank() : 컬럼별로 데이터의 순위를 실수로 반환- 동순위가 있는 경우 .5로 표현
- print(df.rank())
- print(df.rank(ascending=False)) #각 컬럼별로 데이터의 순위 역정렬
**dept_id =1~3, emp_id = 100~400, salary =4000000~8000000
- print(df.rank(axis=1)) #숫자데이터 컬럼끼리(에 대한) 비교 순정렬
- print(df.rank(axis=1,ascending=False))#숫자데이터 컬럼끼리 비교 역정렬
- print(df.T.rank(axis=1,ascending=False)) #각 인원의 컬럼(월급, 사번, 부서번호)별 순위
#(활용)부서별 사원 수 : 부서 별 사원 수 1줄이 한 사람을 의미하기 때문에 가능하다.
- print(df['dept_id'].value_counts()) #부서별 사원수
- print(df['dept_id'].value_counts().rank(ascending=False)) #부서별 사원수 순위
#(활용)지역별 사원 수 :
- print(df['location'].value_counts()) #지역별 사원수
- print(df['location'].value_counts().sort_index(ascending=False)) #지역별 사원수, 알파벳 역정렬#06df_boolean - 조건식을 통한 데이터 추출
#조건식에 참인 데이터만 반환 가능
- print(df.강남>3) #강남 컬럼 데이터의 참 거짓 결과 반환
- print(df[df.강남>3]) #강남 컬럼의 값이 3이상인 행들 반환
- print(df[df['강북'] < 7]) #강북 컬럼의 값이 7이하인 행들 반환
#07drop - 열, 행 삭제 후, 결과 반환
<인덱스 삭제>
#drop()를 사용해 행/열 삭제 결과 반환받기.
- 기본은 원본에 영향없다. inplace=False(default)#df.drop(df.index[0]) : 특정 행 삭제
-실제로 원본 데이터가 삭제되지 않는다.
- print(df.drop(df.index[0])) #index 0 삭제
#df.drop(df.index[[0,3]]) indexing 기능 혼용 가능
- print(df.drop(df.index[[0,3]])) #indexing으로 0,3 동시 삭제
#df.drop(df.index[[0:3]]) slicing 기능 혼용 가능
- print(df.drop(df.index[0:3])) #slicing으로 0,3 동시 삭제
- print(df.drop(df.index[0:3],inplace=True)) #None : 원본도 같이 삭제** df = df.drop(df.index[0:3]) : 수정 내용을 재할당해도 새로 초기화됨
<컬럼 삭제>
#컬럼은 규칙적으로 늘어나는 것이 아니어서, 슬라이싱이 의미가 없다.
#df.drop(['location'],axis=1) indexing으로
- print(df.drop(['location'],axis=1)) #indexing으로 0,3 동시 삭제
#df.drop(['location','dept_id'],axis=1) indexing으로
- print(df.drop(['location','dept_id'],axis=1)) #indexing으로 0,3 동시 삭제
#05df_sort - 인덱스 / 컬럼명 정렬, 특정 컬럼 기준 값 정렬
#sort_index() : 인덱스와 컬럼에대한 정렬 기능
- ex. order by rownum desc
- 인덱스 기준 - 오름차순 정렬이 기본 값
<인덱스를 기준으로 정렬> - print(df.sort_index()) #인덱스를오름차순
- df.sort_index(axis=0,ascending=True) #인덱스를 오름차순(default)
- print(df.sort_index(axis=0,ascending=False)) #DESC : 인덱스를내림차순
<컬럼명을 기준으로 정렬>
- print(df.sort_index(1)) #컬럼명이 오름차순
- print(df.sort_index(axis=1)) #컬럼명이 오름차순
- print(df.sort_index(axis=1,ascending=False)) #컬럼명이 내림차순
#df.sort_values(by=['column name']) : 특정 컬럼 값을 기준으로 정렬
- ex. order by salary asc
- print(df.sort_values(by=['salary'])) #salary 기준 오름차순
- print(df.sort_values(by=['salary'],ascending=False)) #salary 기준 내림차순
#df.rank() : 컬럼별로 데이터의 순위를 실수로 반환
- 동순위가 있는 경우 .5로 표현
- print(df.rank())
- print(df.rank(ascending=False)) #각 컬럼별로 데이터의 순위 역정렬
**dept_id =1~3, emp_id = 100~400, salary =4000000~8000000
- print(df.rank(axis=1)) #숫자데이터 컬럼끼리(에 대한) 비교 순정렬
- print(df.rank(axis=1,ascending=False))#숫자데이터 컬럼끼리 비교 역정렬
- print(df.T.rank(axis=1,ascending=False)) #각 인원의 컬럼(월급, 사번, 부서번호)별 순위
#(활용)부서별 사원 수 : 부서 별 사원 수 1줄이 한 사람을 의미하기 때문에 가능하다.
- print(df['dept_id'].value_counts()) #부서별 사원수
- print(df['dept_id'].value_counts().rank(ascending=False)) #부서별 사원수 순위
#(활용)지역별 사원 수 :
- print(df['location'].value_counts()) #지역별 사원수
- print(df['location'].value_counts().sort_index(ascending=False)) #지역별 사원수, 알파벳 역정렬
--예문 코드 보기--
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
#from numpy import *
#from pandas import Series,DataFrame
# >> Series,DataFrame 는 pd.Series라고 안적고, pd. 까지만 적어도 된다.
print("numpy version",pd.__version__) #pandas version check
print("---------------")
#dict = list,tuple type만 데이터로 사용 가능, set type X
emp = {
'emp_id':[100,101,200,201,300,400],
'name':('kim','lee','choi','han','gang','yoon'),
'salary':[8000000,7000000,7500000,5000000,4000000,6000000],
'dept_id':[1,1,2,2,3,4],
'location':['seoul','seoul','busan','busan','daegu','incheon']
}
df = pd.DataFrame(emp)
print(df)
print("----인덱스 오름차순---")
print(df.sort_index())
#default : df.sort_index(axis=0,ascending=True) #ASC
#sort_index() : 인덱스와 컬럼에대한 정렬 기능
#인덱스 - 오름차순이 기본 값
print("----인덱스 내림차순---")
#order by rownum desc
print(df.sort_index(axis=0,ascending=False)) #DESC
print("---컬럼명이 오름차순------")
print(df.sort_index(1)) #컬럼명이 오름차순
print(df.sort_index(axis=1)) #컬럼명이 오름차순
print("---컬럼 내림차순-----")
print(df.sort_index(axis=1,ascending=False)) #컬럼 내림차순
print("---특정 컬럼 값을 기준으로 정렬-----")
print("---df.sort_values(by=['column name'])-----")
#order by salary asc
print(df.sort_values(by=['salary'])) #salary 기준 오름차순
#order by salary desc
print(df.sort_values(by=['salary'],ascending=False)) #salary 기준 내림차순
print("---df.rank()-----")
#컬럼별로 데이터의 순위를 실수로 반환 - 동순위가 있는 경우 .5로 표현
print(df.rank())
print("--각 컬럼별로 데이터의 순위 역정렬--")
print(df.rank(ascending=False)) #각 컬럼별로 데이터의 순위 역정렬
print("--숫자데이터 컬럼끼리(에 대한) 비교 순정렬--")
#dept_id =1~3, emp_id = 100~400, salary =4000000~8000000
print(df.rank(axis=1)) #숫자데이터 컬럼끼리(에 대한) 비교 순정렬
print("--숫자데이터 컬럼끼리 비교 역정렬---")
print(df.rank(axis=1,ascending=False))#숫자데이터 컬럼끼리 비교 역정렬
print("--각 인원의 컬럼(월급, 사번, 부서번호)별 순위--")
print(df.T.rank(axis=1,ascending=False)) #각 인원의 컬럼(월급, 사번, 부서번호)별 순위
print("---부서별 사원 수-----")
#부서 별 사원 수 1줄이 한 사람을 의미하기 때문에 가능하다.
print(df)
print(df['dept_id'])
print(df['dept_id'].value_counts())
#부서별 사원수 순위
print(df['dept_id'].value_counts().rank(ascending=False))
print("---부서별 사원 수---sort_index-----")
print(df['dept_id'].value_counts().sort_index(ascending=False))
print("---지역별 사원 수---sort_index-----")
print(df['location'])
print(df['location'].value_counts())
print(df['location'].value_counts().sort_index(ascending=False)) #지역별 사원수, 알파벳 역정렬
#06df_boolean - 조건식을 통한 데이터 추출
#조건식에 참인 데이터만 반환 가능
- print(df.강남>3) #강남 컬럼 데이터의 참 거짓 결과 반환
- print(df[df.강남>3]) #강남 컬럼의 값이 3이상인 행들 반환
- print(df[df['강북'] < 7]) #강북 컬럼의 값이 7이하인 행들 반환
--예문 코드 보기--
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
#from numpy import *
#from pandas import Series,DataFrame
# >> Series,DataFrame 는 pd.Series라고 안적고, pd. 까지만 적어도 된다.
print("numpy version",pd.__version__) #pandas version check
print("---------------")
#2차원 넘파이 배열을 데이터 프레임에 삽입
arr = np.arange(16).reshape(4,4)
df = pd.DataFrame(arr)
print(df)
print("---------------")
#문자열 인덱스로 변경
df = pd.DataFrame(arr,index=['a','b','c','d'])
print(df)
print("---------------")
df = pd.DataFrame(arr,index=['a','b','c','d'],columns=['강남','강북','강동','강서'])
print(df)
print("---------------")
df = pd.DataFrame(arr,index=['1월','2월','3월','4월'],columns=['강남','강북','강동','강서'])
print(df)
print("---------------")
print(df['강남'])
print(df.강남)
print("---------------")
print(df.강남>3)
print(df[df.강남>3]) #true값만 반환
print("---------------")
print(df[df['강북'] < 7])
print("---mission------")
#emp 급여가 600만원 이상인 사원정보만
print("---------------")
emp = {
'emp_id':[100,101,200,201,300,400],
'name':('kim','lee','choi','han','gang','yoon'),
'salary':[8000000,7000000,7500000,5000000,4000000,6000000],
'dept_id':[1,1,2,2,3,4],
'location':['seoul','seoul','busan','busan','daegu','incheon']
}
df = pd.DataFrame(emp)
print(df)
print(df[df['salary']>=6000000])
#07drop - 열, 행 삭제 후, 결과 반환
<인덱스 삭제>
#drop()를 사용해 행/열 삭제 결과 반환받기.
- 기본은 원본에 영향없다. inplace=False(default)
#df.drop(df.index[0]) : 특정 행 삭제
-실제로 원본 데이터가 삭제되지 않는다.
- print(df.drop(df.index[0])) #index 0 삭제
#df.drop(df.index[[0,3]]) indexing 기능 혼용 가능
- print(df.drop(df.index[[0,3]])) #indexing으로 0,3 동시 삭제
#df.drop(df.index[[0:3]]) slicing 기능 혼용 가능
- print(df.drop(df.index[0:3])) #slicing으로 0,3 동시 삭제
- print(df.drop(df.index[0:3],inplace=True)) #None : 원본도 같이 삭제
** df = df.drop(df.index[0:3]) : 수정 내용을 재할당해도 새로 초기화됨
<컬럼 삭제>
#컬럼은 규칙적으로 늘어나는 것이 아니어서, 슬라이싱이 의미가 없다.
#df.drop(['location'],axis=1) indexing으로
- print(df.drop(['location'],axis=1)) #indexing으로 0,3 동시 삭제
#df.drop(['location','dept_id'],axis=1) indexing으로
- print(df.drop(['location','dept_id'],axis=1)) #indexing으로 0,3 동시 삭제
--예문 코드 보기--
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
#from numpy import *
#from pandas import Series,DataFrame
# >> Series,DataFrame 는 pd.Series라고 안적고, pd. 까지만 적어도 된다.
print("numpy version",pd.__version__) #pandas version check
emp = {
'emp_id':[100,101,200,201,300,400],
'name':('kim','lee','choi','han','gang','yoon'),
'salary':[8000000,7000000,7500000,5000000,4000000,6000000],
'dept_id':[1,1,2,2,3,4],
'location':['seoul','seoul','busan','busan','daegu','incheon']
}
df = pd.DataFrame(emp)
print(df)
print("=======인덱스 삭제===========")
print("---------------")
#drop()를 사용해 행/열 삭제 결과 반환받기.
#기본은 원본에 영향없다. inplace=False(default)
print(df.index[0])
print("---df.drop(df.index[0])----")
#실제로 원본 데이터가 삭제되지 않는다.
print(df.drop(df.index[0])) #index 0 삭제
#print(df)
print("---------------")
print("--df.drop(df.index[[0,3]]) indexing으로---")
print(df.drop(df.index[[0,3]])) #indexing으로 0,3 동시 삭제
#print(df)
print("---------------")
print("--df.drop(df.index[[0:3]]) slicing으로---")
print(df.drop(df.index[0:3])) #slicing으로 0,3 동시 삭제
#print(df)
print("---------------")
print("--df.drop(df.index[[0:3]]) slicing으로---")
print(df.drop(df.index[0:3],inplace=True)) #None
print("---df - 재할당하면 새로 초기화됨-----")
#df = df.drop(df.index[0:3])
print(df)
print("---------------")
print("=======컬럼 삭제===========")
#컬럼은 슬라이싱이 의미가 없다.
df = pd.DataFrame(emp)
print(df)
print("--df.drop(['location'],axis=1) indexing으로---")
print(df.drop(['location'],axis=1)) #indexing으로 0,3 동시 삭제
print("---------------")
print(df)
print("--df.drop(['location','dept_id'],axis=1) indexing으로---")
print(df.drop(['location','dept_id'],axis=1)) #indexing으로 0,3 동시 삭제
print("---------------")
print(df)