판다스 입문

판다스 데이터프레임과 시리즈( 데이터 프레임 다루기)

jaeyoonlee 2021. 3. 20. 01:49

#6 판다스 chapter 6. 판다스 데이터 프레임 다루기

 

1. 불린 추출하기

 

데이터 프레임도 불린 추출을 할 수 있다. 아래는 데이터 프레임의 Age열에서 Age 열이 평균보다 높은 행만 출력한다.

 

print(scientists[scientists['Age'] > scientists['Age'].mean()])

                   Name        Born        Died  Age     Occupation
1        William Gosset  1876-06-13  1937-10-16   61   Statistician
2  Florence Nightingale  1820-05-12  1910-08-13   90          Nurse
3           Marie Curie  1867-11-07  1934-07-04   66        Chemist
7          Johann Gauss  1777-04-30  1855-02-23   77  Mathematician

 

2. 브로드캐스팅 하기

 

아래는 데이터프레임에 스칼라 연산을 적용 한 것이다. 앞서 배운 시리즈에 스칼라 연산을 적용한 것과 같이 데이터 프레임도 스칼라 연산이 적용 가능하다.

 

print(scientists *2)

                                      Name                  Born  \
0        Rosaline FranklinRosaline Franklin  1920-07-251920-07-25   
1              William GossetWilliam Gosset  1876-06-131876-06-13   
2  Florence NightingaleFlorence Nightingale  1820-05-121820-05-12   
3                    Marie CurieMarie Curie  1867-11-071867-11-07   
4                Rachel CarsonRachel Carson  1907-05-271907-05-27   
5                        John SnowJohn Snow  1813-03-151813-03-15   
6                    Alan TuringAlan Turing  1912-06-231912-06-23   
7                  Johann GaussJohann Gauss  1777-04-301777-04-30   

                   Died  Age                            Occupation  
0  1958-04-161958-04-16   74                        ChemistChemist  
1  1937-10-161937-10-16  122              StatisticianStatistician  
2  1910-08-131910-08-13  180                            NurseNurse  
3  1934-07-041934-07-04  132                        ChemistChemist  
4  1964-04-141964-04-14  112                    BiologistBiologist  
5  1858-06-161858-06-16   90                    PhysicianPhysician  
6  1954-06-071954-06-07   82  Computer ScientistComputer Scientist  
7  1855-02-231855-02-23  154            MathematicianMathematician

 

3. 시리즈와 데이터프레임의 데이터 처리하기

 

아래와 같이 scientists 데이터프레임의 Born과 Died 열의 자료형을 확인하면 object 이다.

 

print(scientists['Born'].dtype)

object

print(scientists['Died'].dtype)

object

 

날짜를 문자열로 저장한 데이터는 datetime 자료형으로 바꾸는 것이 좋다. datetime 자료형을 나중에 더 자세히 살펴보자. 다음은 Born과 Died열의 자료형을 datetime이라는 자료형으로 바꾼다음 format 속성을 '%Y-%m-%d'로 지정하여 날짜형식을 지정한 것이다.

 

born_datetime = pd.to_datetime(scientists['Born'], format = '%Y-%m-%d')
print(born_datetime)

0   1920-07-25
1   1876-06-13
2   1820-05-12
3   1867-11-07
4   1907-05-27
5   1813-03-15
6   1912-06-23
7   1777-04-30

died_datetime = pd.to_datetime(scientists['Died'], format = '%Y-%m-%d')
print(died_datetime)

0   1958-04-16
1   1937-10-16
2   1910-08-13
3   1934-07-04
4   1964-04-14
5   1858-06-16
6   1954-06-07
7   1855-02-23
Name: Died, dtype: datetime64[ns]

 

이제 데이터 프레임에 각각의 값을 새로운 열로 추가해 보겠습니다.

 

scientists['born_dt'], scientists['died_dt'] = (born_datetime, died_datetime)
print(scientists.head())

                   Name        Born        Died  Age    Occupation    born_dt  \
0     Rosaline Franklin  1920-07-25  1958-04-16   37       Chemist 1920-07-25   
1        William Gosset  1876-06-13  1937-10-16   61  Statistician 1876-06-13   
2  Florence Nightingale  1820-05-12  1910-08-13   90         Nurse 1820-05-12   
3           Marie Curie  1867-11-07  1934-07-04   66       Chemist 1867-11-07   
4         Rachel Carson  1907-05-27  1964-04-14   56     Biologist 1907-05-27   

     died_dt  
0 1958-04-16  
1 1937-10-16  
2 1910-08-13  
3 1934-07-04  
4 1964-04-14  

 

 

그리고 아래와 같이 died_dt 열에서 bort_dt를 빼면 과학자가 얼마나 세상을 살다가 떠났는지 계산할 수 있다.

 

scientists['age_days_dt'] = (scientists['died_dt'] - scientists['born_dt'])
print(scientists)

scientists['age_days_dt'] = (scientists['died_dt'] - scientists['born_dt'])
print(scientists)
scientists['age_days_dt'] = (scientists['died_dt'] - scientists['born_dt'])
print(scientists)
                   Name        Born        Died  Age          Occupation  \
0     Rosaline Franklin  1920-07-25  1958-04-16   37             Chemist   
1        William Gosset  1876-06-13  1937-10-16   61        Statistician   
2  Florence Nightingale  1820-05-12  1910-08-13   90               Nurse   
3           Marie Curie  1867-11-07  1934-07-04   66             Chemist   
4         Rachel Carson  1907-05-27  1964-04-14   56           Biologist   
5             John Snow  1813-03-15  1858-06-16   45           Physician   
6           Alan Turing  1912-06-23  1954-06-07   41  Computer Scientist   
7          Johann Gauss  1777-04-30  1855-02-23   77       Mathematician   

     born_dt    died_dt age_days_dt  
0 1920-07-25 1958-04-16  13779 days  
1 1876-06-13 1937-10-16  22404 days  
2 1820-05-12 1910-08-13  32964 days  
3 1867-11-07 1934-07-04  24345 days  
4 1907-05-27 1964-04-14  20777 days  
5 1813-03-15 1858-06-16  16529 days  
6 1912-06-23 1954-06-07  15324 days  
7 1777-04-30 1855-02-23  28422 days 

 

4. 시리즈와 데이터프레임의 데이터 섞기

 

가끔 데이터를 섞어야 하는 경우도 있다. 판다스는 시리즈나 데이터프레임의 데이터를 무작위로 섞어볼 수도 있다.

 

print(scientists['Age'])

0    37
1    61
2    90
3    66
4    56
5    45
6    41
7    77
Name: Age, dtype: int64

 

Age열의 데이터를 섞으려면 random 라이브러리를 불러온 다음 random 라이브러리에 데이터를 섞어주는 shuffle 메서드가 있다.

 

import random

random.seed(42)
random.shuffle(scientists['Age'])
print(scientists['Age'])

0    66
1    56
2    41
3    77
4    90
5    45
6    37
7    61
Name: Age, dtype: int64

 

5. 데이터프레임의 열 삭제하기

 

때로는 열을 통째로 삭제해야하는 경우도 있는데 이 때 drop 메서드를 사용하여 삭제할 수 있다.

 

print(scientists.columns)

Index(['Name', 'Born', 'Died', 'Age', 'Occupation', 'born_dt', 'died_dt',
       'age_days_dt'],
      dtype='object')
      
scientists_dropped = scientists.drop(['Age'], axis=1)
print(scientists_dropped.columns)

Index(['Name', 'Born', 'Died', 'Occupation', 'born_dt', 'died_dt',
       'age_days_dt'],
      dtype='object')

 

drop 메서드에 첫 번째 인자에 열 이름을 리스트에 담아 전달하고 두 번째 인자에는 axis=1 을 전달하면 Age 열을 삭제할 수 있다.

 

6.  데이터 저장하고 불러오기

 

* 피클로 저장하기

 

피클은 데이터를 바이너리 형태로 직렬화한 오브젝트를 저장하는 방법이다. 피클로 저장하면 스프레드시트보다 더 작은 용량으로 데이터를 저장할 수 있어 매우 편리하다.

 

names = scientists['Name']
names.to_pickle('../output/scientists_names_series.pickle')

 

데이터 프레임도 아래와 같이 피클로 저장 가능하다.

 

scientists.to_pickle('../output/scientists_names_series.pickle')

 

피클 데이터는 반드시 read_pickle 메서드로 읽어 들여야 한다.

 

scientist_name_from_pickle = pd.read_pickle('../output/scientists_names_series.pickle')
print(scientist_name_from_pickle)

scientist_name_from_pickle = pd.read_pickle('C:/Users/이재윤/Downloads/doit_pandas-master/doit_pandas-master/output/scientists_names_series.pickle')
print(scientist_name_from_pickle)
scientist_name_from_pickle = pd.read_pickle('C:/Users/이재윤/Downloads/doit_pandas-master/doit_pandas-master/output/scientists_names_series.pickle')
print(scientist_name_from_pickle)
                   Name        Born        Died  Age          Occupation  \
0     Rosaline Franklin  1920-07-25  1958-04-16   37             Chemist   
1        William Gosset  1876-06-13  1937-10-16   61        Statistician   
2  Florence Nightingale  1820-05-12  1910-08-13   90               Nurse   
3           Marie Curie  1867-11-07  1934-07-04   66             Chemist   
4         Rachel Carson  1907-05-27  1964-04-14   56           Biologist   
5             John Snow  1813-03-15  1858-06-16   45           Physician   
6           Alan Turing  1912-06-23  1954-06-07   41  Computer Scientist   
7          Johann Gauss  1777-04-30  1855-02-23   77       Mathematician   

     born_dt    died_dt age_days_dt  
0 1920-07-25 1958-04-16  13779 days  
1 1876-06-13 1937-10-16  22404 days  
2 1820-05-12 1910-08-13  32964 days  
3 1867-11-07 1934-07-04  24345 days  
4 1907-05-27 1964-04-14  20777 days  
5 1813-03-15 1858-06-16  16529 days  
6 1912-06-23 1954-06-07  15324 days  
7 1777-04-30 1855-02-23  28422 days  

scientists_from_pickle = pd.read_pickle('../output/scientists_names_series.pickle')
print(scientists_from_pickle)

                  Name        Born        Died  Age          Occupation  \
0     Rosaline Franklin  1920-07-25  1958-04-16   37             Chemist   
1        William Gosset  1876-06-13  1937-10-16   61        Statistician   
2  Florence Nightingale  1820-05-12  1910-08-13   90               Nurse   
3           Marie Curie  1867-11-07  1934-07-04   66             Chemist   
4         Rachel Carson  1907-05-27  1964-04-14   56           Biologist   
5             John Snow  1813-03-15  1858-06-16   45           Physician   
6           Alan Turing  1912-06-23  1954-06-07   41  Computer Scientist   
7          Johann Gauss  1777-04-30  1855-02-23   77       Mathematician   

     born_dt    died_dt age_days_dt  
0 1920-07-25 1958-04-16  13779 days  
1 1876-06-13 1937-10-16  22404 days  
2 1820-05-12 1910-08-13  32964 days  
3 1867-11-07 1934-07-04  24345 days  
4 1907-05-27 1964-04-14  20777 days  
5 1813-03-15 1858-06-16  16529 days  
6 1912-06-23 1954-06-07  15324 days  
7 1777-04-30 1855-02-23  28422 days  

 

* CSV 파일과 TSV 파일로 저장하기

 

CSV 파일은 데이터를 쉼표로 구분하여 저장한 파일이고 TSV 파일은 데이터를 탭으로 구분하여 저장한 파일이다. 각각의 파일을 텍스트 편집기로 열어보면 데이터가 쉼표, 탭으로 구분되어 있는것을 알 수 있다.

to_csv 메서드로 시리즈와 데이터프레임을 CSV 파일로 저장할 수 있다. 이때  sep 인자를 추가하여 '\t' 를 지정하고 확장자를 '.tsv' 로 지정하면 TSV 파일로 저장할 수 있다.

 

names.to_csv('C:/Users/이재윤/Downloads/doit_pandas-master/doit_pandas-master/output/scientists_names_series.pickle')
scientists.to_csv('C:/Users/이재윤/Downloads/doit_pandas-master/doit_pandas-master/output/scientists_names_series.pickle', sep='\t')

 

 

출처 :  데이터 분석을 위한 판다스 입문