3. 판다스 데이터프레임과 시리즈¶
데이터프레임과 시리즈는 리스트나 딕셔너리와 비슷하지만 데이터를 다루는 데 더 특화되어있다. 리스트아 딕셔너리는 많은 양의 데이터를 저장하거나 데이터를 조작할 수 있는 메서드가 많지 않습니다. 반면에 판다스의 데이터프레임과 시리즈는 많은 양의 데이터를 저장할 수 있을 뿐만 아니라 스프레드시트 프로그램을 사용하는 것처럼 행과 열 단위로 원하는 데이터를 조작할 수 있는 다양한 속성과 메서드를 제공합니다.그러면 데이터프레임과 시리즈에 대해 좀 더 자세히 알아보겠습니다.
3-1 나만의 데이터 만들기¶
3-2 시리즈 다루기 - 기초¶
3-3 시리즈 다루기 - 응용¶
3-4 데이터프레임 다루기¶
3-5 시리즈와 데이터프레임의 데이터 처리하기¶
3-6 데이터 저장하고 불러오기¶
import pandas as pd
s = pd.Series(['banana',42])
print(s)
0 banana
1 42
dtype: object
2.¶
인덱스는 보통 0부터 시작한다고 설명했던 것을 기억하나요? 하지만 시리즈를 생성할 때 문자열을 인덱스로 지정할 수도 있습니다. 문자열을 인덱스로 지정하려면 Series메서드의 index 인자를 통해 인덱스로 사용하고자 하는 문자열을 리스트에 담아 전달하면 됩니다.
s = pd.Series(['Wes McKinney','Creator of Pandas'])
print(s)
0 Wes McKinney
1 Creator of Pandas
dtype: object
s = pd.Series(['Wes McKinney','Creator of pandas'], index = ['Person','Who'])
print(s)
Person Wes McKinney
Who Creator of pandas
dtype: object
3. 데이터프레임 만들기¶
데이터프레임을 만들기 위해서는 딕셔너리를 DataFrame 클래스에 전달해야 합니다.
scientists = pd.DataFrame({
'Name':['Rosaline Franklin', 'William Gosset'],
'Occupation':['Chemist','Statistician'],
'Born':['1920-07-25', '1876-06-13'],
'Died':['1958-04-16', '1937-10-16'],
'Age':[37, 61]})
print(scientists)
Name Occupation Born Died Age
0 Rosaline Franklin Chemist 1920-07-25 1958-04-16 37
1 William Gosset Statistician 1876-06-13 1937-10-16 61
scientists = pd.DataFrame({
'Name': ['Rosaline Franklin', 'William Gosset'],
'Occupation' : ['Chemist', 'Statistician'],
'Born': ['1920-07-05', '1876-06-13'],
'Died': ['1958-04-16', '1937-10-16'],
'Age': [37,61]}
)
scientists
Name | Occupation | Born | Died | Age | |
---|---|---|---|---|---|
0 | Rosaline Franklin | Chemist | 1920-07-05 | 1958-04-16 | 37 |
1 | William Gosset | Statistician | 1876-06-13 | 1937-10-16 | 61 |
4.¶
시리즈와 마찬가지로 데이터프레임도 인덱스를 따로 지증하지 않으면 인덱스를 0부터 자동으로 생성한다. 인덱스를 따로 지정하려면 index 인자에 리스트를 전달하면 된다. 또한, columns인자를 사용하면 데이터프레임의 열 순서를 지정할 수 있다.
scientists = pd.DataFrame(
data={'Occupation' : ['Chemist', 'Statistician'],
'Born': ['1920-07-05', '1876-06-13'],
'Died': ['1958-04-16', '1937-10-16'],
'Age': [37,61]},
index=['Rosaline Franklin', 'William Gosset'],
columns=['Occupation', 'Born', 'Age', 'Died']
)
print(scientists)
Occupation Born Age Died
Rosaline Franklin Chemist 1920-07-05 37 1958-04-16
William Gosset Statistician 1876-06-13 61 1937-10-16
3-2 시리즈 다루기 - 기초¶
판다스의 데이터 구성 기본 단위는 시리즈이다. 시리즈에 대해 알아보자.
scientists = pd.DataFrame(
data={'Occupation' : ['Chemist', 'Statistician'],
'Born': ['1920-07-05', '1876-06-13'],
'Died': ['1958-04-16', '1937-10-16'],
'Age': [37,61]},
index=['Rosaline Franklin', 'William Gosset'],
columns=['Occupation', 'Born', 'Age', 'Died']
)
print(scientists)
Occupation Born Age Died
Rosaline Franklin Chemist 1920-07-05 37 1958-04-16
William Gosset Statistician 1876-06-13 61 1937-10-16
2¶
데이터프레임에서 시리즈를 선택하려면 loc속성에 인덱스를 전달하면 된다.
first_row = scientists.loc['William Gosset']
type(first_row)
pandas.core.series.Series
first_row
Occupation Statistician
Born 1876-06-13
Age 61
Died 1937-10-16
Name: William Gosset, dtype: object
first_row.index
Index(['Occupation', 'Born', 'Age', 'Died'], dtype='object')
2. values 속성 사용¶
first_row.values
array(['Statistician', '1876-06-13', 61, '1937-10-16'], dtype=object)
3. key 메서드 사용¶
keys는 속성이 아니라 메서드라는 표현을 사용했다. keys 메서드는 index속성과 같은 역할은 한다. 즉, 과정1의 결과와 동일한 결과값을 얻을 수 있다.
first_row.keys()
Index(['Occupation', 'Born', 'Age', 'Died'], dtype='object')
4. index 속성 응용¶
first_row.index[0]
'Occupation'
5. keys 메서드 응용¶
first_row.keys()[0]
'Occupation'
시리즈의 기초 통계 메서드 사용¶
시리즈에는 keys메서드 외에도 다양한 메서드가 있다. mean, min, max, std메서드의 사용방법을 알아보자.
1.¶
scientists의 Ages열을 추출 해보자.
ages = scientists['Age']
ages
Rosaline Franklin 37
William Gosset 61
Name: Age, dtype: int64
2.¶
시리즈를 구성하는 데이터가 정수이면 mean, min, max, std와 같은 통계 메서드를 사용할 수 있다.
print(ages.mean()) # ages 평균
print(ages.min()) # ages 최소값
print(ages.max()) # ages 최대값
print(ages.std()) # age 표준편차
49.0
37
61
16.97056274847714
시리즈 메서드 정리¶
시리즈 메서드 | 설명 |
---|---|
append | 2개 이상의 시리즈 연결 |
describe | 요약 통계량 계산 |
drop_duplicates | 중복값이 없는 시리즈 변환 |
equals | 시리즈에 해당 값을 가진 요소가 있는지 확인 |
get_values | 시리즈 값 구하기(values 속성과 동일) |
isin | 시리즈에 포함관 값이 있는지 확인 |
min | 최소값 |
max | 최대값 |
mean | 평균값 |
median | 중간값 |
replace | 특정 값을 가진 시리즈 값을 교체 |
sample | 시리즈에서 임의의 값을 변환 |
sort_values | 값을 정렬 |
to_frame | 시리즈를 데이터프레임으로 변환 |
scientists = pd.read_csv("./data/scientists.csv")
2.¶
ages = scientists['Age']
print(ages.max())
print(ages.mean())
90
59.125
3.¶
이제 불린 추출 사용법을 알아보자. 예로 평균 나이보다 나이가 많은 사람의 데이터를 추출하기 위해선 다음의 코드를 사용하면 된다.
print(ages[ages < ages.mean()])
0 37
4 56
5 45
6 41
Name: Age, dtype: int64
4.¶
이번에는 이 값을 TF로 표현을 해보자
print(ages > ages.mean())
0 False
1 True
2 True
3 True
4 False
5 False
6 False
7 True
Name: Age, dtype: bool
5.¶
위에서 보듯이 리스트 형태로 True/False를 시리즈에 전달 하면 True만 필터링 해서 추출을 하는데 이것을 불린 추출이라고 한다.
manual_bool_values = [True, True, False, False, True, True, False, True]
ages[manual_bool_values]
0 37
1 61
4 56
5 45
7 77
Name: Age, dtype: int64
시리즈와 브로드캐스팅¶
시리즈나 데이터프레임에 있는 모든 데이터에 대해 한 번에 연산하는 것을 브로드캐스팅(Broadcasting)이라고 한다. 시리즈처럼 여러 개의 값을 가진 데이터를 벡터라고 하고 단순 크기를 나타내는 데이터는 스칼라라고 한다.
ages + ages
0 74
1 122
2 180
3 132
4 112
5 90
6 82
7 154
Name: Age, dtype: int64
ages * ages
0 1369
1 3721
2 8100
3 4356
4 3136
5 2025
6 1681
7 5929
Name: Age, dtype: int64
2.¶
이번에는 벡터에 스칼라를 연산해보자.
ages + 100
0 137
1 161
2 190
3 166
4 156
5 145
6 141
7 177
Name: Age, dtype: int64
ages * 2
0 74
1 122
2 180
3 132
4 112
5 90
6 82
7 154
Name: Age, dtype: int64
3.¶
길이가 서로 다른 벡터를 연산하려면? 시리즈와 시리즈를 연산하는 경우 같은 인덱스의 값만 계산하게 된다. 다음은 데이터의 개수가 2개인 시리즈와 8개인 시리즈를 더한것이다. 결과값을 보면 인덱스가 일치한 상위두개의 값만 계산을 하였고 나머지는 누락값(NaN)으로 처리가 된다.
pd.Series([1,100])
0 1
1 100
dtype: int64
ages + pd.Series([1,100])
0 38.0
1 161.0
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
dtype: float64
4.¶
다음은 sort_index 메서드를 사용한 것이다. 이때 ascending 인자로 False를 전달하여 인덱스 역순으로 데이터를 정렬한 결과이다.
rev_ages = ages.sort_index(ascending=False)
rev_ages
7 77
6 41
5 45
4 56
3 66
2 90
1 61
0 37
Name: Age, dtype: int64
5.¶
이번에는 인덱스를 역순으로 구성한 rev_age와 ages를 더하고, 동시에 ages에 2를 곱한 값을 비교해보자. 결과는 같을텐데, ages의 인덱스와 rev_ages의 인덱스가 일치하는 값끼리 연산을 수행했기 때문이다
print(ages * 2)
print(ages + rev_ages)
0 74
1 122
2 180
3 132
4 112
5 90
6 82
7 154
Name: Age, dtype: int64
0 74
1 122
2 180
3 132
4 112
5 90
6 82
7 154
Name: Age, dtype: int64
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.¶
시리즈에 리스트로 참,거짓을 전달하여 데이터 추출을 했었다. 참, 거짓을 담은 리스트릴 bool 벡터라고 부릅니다. 만약 bool 벡터의 길이가 데이터프레임의 행길이보다 짧으면 bool 벡터의 길이만큼만 연산합니다. 다음은 데이터프레임의 loc속성에 길이가 4인 bool 벡터를 전달한 것입니다.
print(scientists.loc[[True, True, False, True]])
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-35-894b58968834> in <module>
----> 1 print(scientists.loc[[True, True, False, True]])
c:\users\금동훈\appdata\local\programs\python\python39\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
893
894 maybe_callable = com.apply_if_callable(key, self.obj)
--> 895 return self._getitem_axis(maybe_callable, axis=axis)
896
897 def _is_scalar_access(self, key: Tuple):
c:\users\금동훈\appdata\local\programs\python\python39\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
1102 return self._get_slice_axis(key, axis=axis)
1103 elif com.is_bool_indexer(key):
-> 1104 return self._getbool_axis(key, axis=axis)
1105 elif is_list_like_indexer(key):
1106
c:\users\금동훈\appdata\local\programs\python\python39\lib\site-packages\pandas\core\indexing.py in _getbool_axis(self, key, axis)
910 # caller is responsible for ensuring non-None axis
911 labels = self.obj._get_axis(axis)
--> 912 key = check_bool_indexer(labels, key)
913 inds = key.nonzero()[0]
914 return self.obj._take_with_is_copy(inds, axis=axis)
c:\users\금동훈\appdata\local\programs\python\python39\lib\site-packages\pandas\core\indexing.py in check_bool_indexer(index, key)
2280 # key may contain nan elements, check_array_indexer needs bool array
2281 result = pd_array(result, dtype=bool)
-> 2282 return check_array_indexer(index, result)
2283
2284
c:\users\금동훈\appdata\local\programs\python\python39\lib\site-packages\pandas\core\indexers.py in check_array_indexer(array, indexer)
483 # GH26658
484 if len(indexer) != len(array):
--> 485 raise IndexError(
486 f"Boolean index has wrong length: "
487 f"{len(indexer)} instead of {len(array)}"
IndexError: Boolean index has wrong length: 4 instead of 8
3. 브로드캐스팅하기¶
데이터프레임에 스칼라 연산을 적용하면 어떻게 될까요? 앞으로 시리즈에 스칼라 연산을 적용할 때는 모든 요소에 스칼라를 적용하여 연산했습니다. 데이터프레임도 마찬가지입니다. scientists 데이터프레임에 2를 곱하면 정수 데이터는 2를 곱할 숫자가 되고 문자열 데이터는 문자열이 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-5 시리즈와 데이터프레임의 데이터 처리하기¶
지금까지는 시리즈와 데이터프레임에서 데이터를 추출하는 여러 방법에 대해 알아보았습니다. 이번에는 시리즈와 데이터프레임에 있는 데이터를 처리하는 방법에 대해 알아보겠습니다.
시리즈와 데이터프레임의 데이터 처리하기¶
1. 열의 자료형 바구끼와 새로운 열 추가하기¶
scientists 데이터프레임의 Born 과 Died 열의 자료형을 확인해 보겠습니다. 각각의 자료형은 문자열(오브젝트)입니다.
print(scientists['Born'].dtype)
object
print(scientists['Died'].dtype)
object
2.¶
날짜를 문자열로 저장한 데이터는 시간 관련 작업을 할 수 있도록 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
Name: Born, dtype: datetime64[ns]
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]
3.¶
과정 2에서 각 데이터의 자료형을 datetime으로 바꿔 born_datetime, died_datetime에 저장했으니 이제 데이터프레임에 각각의 값을 새로운 열로 추가해 보겠습니다. 다음은 scientists 데이터프레임에 born_dt, died_dt 열을 추가한 것입니다. shape속성으로 데이터프레임의 형태를 살펴보면 (8,5)에서 (8,7)로 2개의 열이 추가되었다는 것을 알 수 있습니다.
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
print(scientists.shape)
(8, 7)
4.¶
이제 시간 계산을 해볼까요? died_dt 열에서 born_dt를 빼면 과학자가 얼마 동안 세상을 살다나 떠났는지 계산할 수 있습니다. 만약 결괏값이 제대로 출력되지 않는다면 과정 1~3을 다시 실행해보세요.
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
5. 시리즈,데이터프레임의 데이터 섞기¶
가끔은 데이터를 적당히 섞어야 하는 경우도 있습니다. 판다스는 시리즈나 데이터프레임의 데이터를 무작위로 섞어볼 수도 있습니다. 먼저 Age값을 출력하여 살펴보겠습니다.
print(scientists['Age'])
0 37
1 61
2 90
3 66
4 56
5 45
6 41
7 77
Name: Age, dtype: int64
6.¶
Age열의 데이터를 섞으려면 random 라이브러리를 불러와야 합니다. random 라이브러리에는 데이터를 섞어주는 shuffle 메서드가 있습니다. shuffle 메서드에 Age 열을 전달하여 데이터를 섞어보겠습니다. Age 열을 출력해 보면 인덱스 0~7에 해당하는 값이 잘 섞여 있음을 알 수 있습니다.
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
c:\users\금동훈\appdata\local\programs\python\python39\lib\random.py:363: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
x[i], x[j] = x[j], x[i]
7. 데이터프레임의 열 삭제하기¶
때로는 열을 통째로 삭제해야 하는 경우도 있습니다. 먼저 scientists 데이터프레임의 열을 확인해 보겠습니다.
print(scientists.columns)
Index(['Name', 'Born', 'Died', 'Age', 'Occupation', 'born_dt', 'died_dt',
'age_days_dt'],
dtype='object')
8.¶
데이터프레임에서 열을 삭제하려면 데이터프레임의 drop 메서드를 사용해야 합니다. shuffle 메서드로 섞은 Age 열을 삭제해 보겠습니다. drop메서드의 첫 번째 인자에 열 이름을 리스트에 담아 전달하고 두 번째 인자에는 axis = 1을 전달하면 Age 열을 삭제할 수 있습니다.
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')
3-6 데이터 저장하고 불러오기¶
지금까지 데이터를 추출하고 처리하는 방법에 대해 알아보았습니다. 일종의 '데이터 가공 처리'를 거친 것이죠. 이렇게 잘 가공한 데이터는 안전하게 보관해야 다음에 또 사용할 수 있습니다. 판다스는 데이터를 저정하는 다양한 방법을 제공합니다. 여기서는 가공한 데이터를 피클,CSV,TSV파일로 저장하고 다시 불러오는 방법에 대해 살펴봅니다.
데이터를 피클,CSV,TSV 파일로 저장하고 불러오기¶
1. 피클로 저장하기¶
피클은 데이터를 바이너리 형태로 직렬화한 오브젝트를 저장하는 방법입니다. 피클로 저장하면 스프레드시트보다 더 작은 용량으로 데이터를 저장할 수 있어 매우 편리합니다. 시리즈를 피클로 저장하러면 to_pickle 메서드를 사용하면 되는데, 이때 저장 경로를 문자열로 전달해야 합니다.
names = scientists['Name']
names.to_pickle('./output/scientists_names_series.pickle')
2. 데이터프레임도 피클로 저장할 수 있습니다.¶
scientists.to_pickle('./output/scientists_df.pickle')
3.¶
피클은 바이너리 형태의 오브젝트이기 때문에 저장된 피클 데이터를 편집기와 같은 프로그램으로 열어보면 이상한 문자가 나타납니다.피클 데이터는 반드시 read_pickle 메서드로 읽어 들여야 합니다.
scientist_names_from_pickle = pd.read_pickle('./output/scientists_names_series.pickle')
print(scientist_names_from_pickle)
0 Rosaline Franklin
1 William Gosset
2 Florence Nightingale
3 Marie Curie
4 Rachel Carson
5 John Snow
6 Alan Turing
7 Johann Gauss
Name: Name, dtype: object
scientists_from_pickle = pd.read_pickle('./output/scientists_df.pickle')
print(scientists_from_pickle)
Name Born Died Age Occupation \
0 Rosaline Franklin 1920-07-25 1958-04-16 66 Chemist
1 William Gosset 1876-06-13 1937-10-16 56 Statistician
2 Florence Nightingale 1820-05-12 1910-08-13 41 Nurse
3 Marie Curie 1867-11-07 1934-07-04 77 Chemist
4 Rachel Carson 1907-05-27 1964-04-14 90 Biologist
5 John Snow 1813-03-15 1858-06-16 45 Physician
6 Alan Turing 1912-06-23 1954-06-07 37 Computer Scientist
7 Johann Gauss 1777-04-30 1855-02-23 61 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. CSC 파일과 TSV 파일로 저장하기¶
CSV 파일은 데이터를 쉼표로 구분하여 저장한 파일이고 TSV 파일은 데이터를 탭으로 구분하여 저장한 파일입니다. 실제로 각각의 파일을 텍스트 편집기로 열어 살펴보면 데이터가 쉼표, 탭으로 구분되어 있는 것을 알 수 있습니다. 다음은 data 폴더의 'concat_1.csv' 파일과 'gapminder.tsv' 파일을 비주얼 스튜디오 코드라는 텍스트 편집기로 열어 살펴본 것입니다. 비주얼 스튜디오 코드가 없다면 여러분의 컴퓨터에 설치된 텍스트 편집기로 파일을 열어보세요.
5.¶
to_csv 메서드로 시리즈(names)와 데이터프레임(scientsits)을 CSV 파일로 저장할 수 있습니다. 이때 sep 인자를 추가하여 '\t'를 지정하고 파일의 확장자를 '.tsv'로 지정하면 TSV 파일로 저장할 수 있습니다.
names.to_csv('./output/scientist_names_series.csv')
scientists.to_csv('./output/scientists_df.tsv', sep='\t')
마무리하며¶
이 장에서는 시리즈와 데이터 프레임을 좀더 자세히 다루어 보았습니다. 다음 장부터는 파이썬과 판다스로 그래프를 그리기 위한 기초 개념을 살펴봅니다. 데이터 분석에서 가장 중요한 요소 중 하나인 데이터 시각화에 대한 내용이 시작되는 것이죠.
출처 : " Do it 데이터 분석을 위한 판다스 입문 "
출처 : " Do it 데이터 분석을 위한 판다스 입문 "
'Do it 판다스 입문' 카테고리의 다른 글
Do it pandas Chapter 6. 누락값 처리하기 (0) | 2021.03.28 |
---|---|
Do it pandas Chapter 5. 데이터 연결하기 (0) | 2021.03.26 |
Do it pandas Chapter 4. 그래프 그리기 (이어서) (0) | 2021.03.25 |
Do it pandas Chapter 4. 그래프 그리기 (0) | 2021.03.24 |
Do it Pandas Chapter 2. 판다스 시작하기 (0) | 2021.03.22 |