[Pandas] Series

DU·2024년 9월 25일
1

Python

목록 보기
5/8
post-thumbnail

1. Pandas Series란?

Series는 Pandas의 기본 데이터 구조 중 하나로, 1차원 배열과 유사합니다. Series는 데이터와 함께 인덱스를 가지며, 인덱스를 통해 데이터를 쉽게 접근할 수 있습니다.

import pandas as pd

# 기본 Series 생성
s = pd.Series([1, 2, 3, 4, 5])
print(s)

이 코드는 기본적인 Series를 생성하고 출력합니다. 결과는 다음과 같습니다:

0    1
1    2
2    3
3    4
4    5
dtype: int64

2. 리스트로 Series 생성

리스트를 이용하여 Series 객체를 생성할 수 있습니다.

data = [10, 20, 30, 40, 50]
s = pd.Series(data)
print(s)

결과:

0    10
1    20
2    30
3    40
4    50
dtype: int64

3. 딕셔너리로 Series 생성

딕셔너리를 이용해 Series를 생성하면, 딕셔너리의 키가 인덱스로, 값이 데이터로 설정됩니다.

data = {'a': 1, 'b': 2, 'c': 3}
s = pd.Series(data)
print(s)

결과:

a    1
b    2
c    3
dtype: int64

4. 인덱스를 직접 지정하여 생성

데이터와 함께 인덱스를 직접 지정할 수 있습니다.

data = [100, 200, 300]
index = ['apple', 'banana', 'cherry']
s = pd.Series(data, index=index)
print(s)

결과:

apple     100
banana    200
cherry    300
dtype: int64

5. 스칼라 값으로 Series 생성

단일 값을 이용하여 Series를 생성하고, 특정 길이만큼 복제할 수 있습니다.

s = pd.Series(5, index=['a', 'b', 'c', 'd'])
print(s)

결과:

a    5
b    5
c    5
d    5
dtype: int64

6. 데이터 타입 지정하여 생성

dtype 옵션을 사용해 Series의 데이터 타입을 지정할 수 있습니다.

data = [1, 2, 3, 4]
s = pd.Series(data, dtype='float64')
print(s)

결과:

0    1.0
1    2.0
2    3.0
3    4.0
dtype: float64

0개의 댓글