Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
Tags
- data
- len()
- dendrogram
- 분류 결과표
- DataAccess
- 덴드로그램
- DataFrame
- count()
- numpy
- nan
- append()
- sklearn
- elbow method
- 최댓값
- Python
- insert()
- function
- string
- matplotlib
- wcss
- IN
- del
- analizer
- Dictionary
- hierarchical_clustering
- pandas
- 반복문
- 최솟값
- Machine Learning
- list
Archives
- Today
- Total
개발공부
[Python] Pandas Dataframe 조건을 만족하는 데이터 얻기, apply()(=함수를 이용해 얻기) 본문
Python/Pandas
[Python] Pandas Dataframe 조건을 만족하는 데이터 얻기, apply()(=함수를 이용해 얻기)
mscha 2022. 5. 3. 13:12import pandas as pd
df = pd.DataFrame({'Employee ID':[111, 222, 333, 444],
'Employee Name':['Chanel', 'Steve', 'Mitch', 'Bird'],
'Salary [$/h]':[35, 29, 38, 20],
'Years of Experience':[3, 4 ,9, 1]})
df

판다스 데이터프레임에서는 True와 False로 결과가 나오는 식을 [ ] 안에 입력하면 그에 맞는 데이터를 찾을 수 있다.
아래의 예로 이해해 보자
# 경력이 3년 이상인 사람의 데이터를 가져오기
>>> df['Years of Experience'] >= 3
0 True
1 True
2 True
3 False
Name: Years of Experience, dtype: bool
>>> df.loc[ df['Years of Experience'] >= 3, ]

위와 같이 df에서 조건에 만족하는 행들을 찾은 후 이를 loc함수를 이용해서 True인 행들만 찾을 수 있다.
다른 예들을 계속 봐보자.
# 경력이 3년 이상인 사람의, 이름과 시급 정보를 가져오시오
# [조건을 만족하는 행, 얻고자하는 열]
df.loc[ df['Years of Experience'] >= 3, ['Employee Name', 'Salary [$/h]']]

# 경력이 3년 이상이고, 8년 이하인 사람의 데이터를 가져오시오
cond = (df['Years of Experience'] >= 3) & (df['Years of Experience'] <= 8)
df.loc[ cond , ]

위와 같이 &와 | 기호를 통해 and, or 연산도 할 수 있다.
apply()
- 함수를 사용하여 원하는 데이터를 저장할 수 있다.
# 시급이 30이상이면, A 그룹
# 그렇지 않으면 B 그룹이라고 구분할 것이다.
# 따라서 새로운 컬럼 gorup 컬럼을 만들어서, A 나 B 값으로 저장하시오.
def grouping(salary) :
if salary >=30:
return 'A'
else :
return 'B'
df['Salary [$/h]'].apply(grouping)

df['group'] = df['Salary [$/h]'].apply(grouping)
df

'Python > Pandas' 카테고리의 다른 글
| [Python] Pandas Dataframe 합치기 concat(), merge() (0) | 2022.05.03 |
|---|---|
| [Python] Pandas 데이터 정렬하기 sort_values(), sort_index() (0) | 2022.05.03 |
| [Python]Pandas 카테고리컬 데이터 확인하기, 이를 묶어 처리하기 groupby() (0) | 2022.05.03 |
| [Python] Pandas Dataframe NaN 다루기 (0) | 2022.05.02 |
| [Python] Pandas Dataframe 인덱스, 컬럼명 변경하기(rename()), 컬럼을 인덱스로 사용하기(set_index(),reset_index()) (0) | 2022.05.02 |