-
[파이썬]Pandas 행,열 생성 및 수정하기Pandas 2021. 2. 4. 03:45반응형
Untitled4 행, 열 생성 / 수정¶
열 생성¶
In [39]:import pandas as pd people = [ {'name': 'Kim', 'midterm': 90, 'final': 85}, {'name': 'Lee', 'midterm': 80, 'final': 75}, {'name': 'Choi', 'midterm': 65, 'final':100} ] df = pd.DataFrame(people)
In [40]:df
Out[40]:name midterm final 0 Kim 90 85 1 Lee 80 75 2 Choi 65 100 In [41]:df['total'] = df['midterm'] + df['final'] df
Out[41]:name midterm final total 0 Kim 90 85 175 1 Lee 80 75 155 2 Choi 65 100 165 In [43]:df['avg'] = df['total'] / 2 df
Out[43]:name midterm final total avg 0 Kim 90 85 175 87.5 1 Lee 80 75 155 77.5 2 Choi 65 100 165 82.5 In [54]:grades = [] for row in df['avg']: if row >85: grades.append('A') elif row > 80: grades.append('B') else: grades.append('F') df['grade'] = grades df
Out[54]:name midterm final total avg grade 0 Kim 90 85 175 87.5 A 1 Lee 80 75 155 77.5 F 2 Choi 65 100 165 82.5 B 함수와 apply를 이용하기¶
In [55]:def pass_or_fail(row): if row != 'F': return 'Pass' else: return 'Fail'
In [56]:df.grade = df.grade.apply(pass_or_fail) df
Out[56]:name midterm final total avg grade 0 Kim 90 85 175 87.5 Pass 1 Lee 80 75 155 77.5 Fail 2 Choi 65 100 165 82.5 Pass 행 생성하기¶
In [59]:df2 = pd.DataFrame([ ['Park', 88, 90]], columns=['name', 'midterm', 'final'] ) df2
Out[59]:name midterm final 0 Park 88 90 In [60]:df.append(df2, ignore_index=True)
Out[60]:name midterm final total avg grade 0 Kim 90 85 175.0 87.5 Pass 1 Lee 80 75 155.0 77.5 Fail 2 Choi 65 100 165.0 82.5 Pass 3 Park 88 90 NaN NaN NaN In [ ]:반응형'Pandas' 카테고리의 다른 글
[파이썬]Pandas groupby를 이용해 같은 항목을 묶어보자 (0) 2021.02.04 [파이썬]Pandas 행과 열 선택하기 (0) 2021.02.04 [파이썬]Pandas DataFrame만들기 (0) 2021.02.04 [파이썬] DataFrame에서 누락값 처리하기 (0) 2021.01.15 [파이썬] 판다스 DataFrame에서 열 선택하기 (0) 2021.01.08