Python을 사용한 데이터 분석 및 시각화
Python은 강력한 라이브러리와 데이터 관리 도구로 인해 데이터 분석 언어로 널리 사용됩니다. 이러한 라이브러리 중에는 데이터 탐색 조작 및 분석을 더 쉽게 해주는 Pandas가 있습니다. 우리는 사용할 것이다 팬더 라는 데이터세트를 분석하기 위해 국가 데이터.csv 캐글에서. 이 데이터를 사용하는 동안 Pandas의 몇 가지 중요한 개념도 소개합니다.
1. 설치
pandas를 설치하는 가장 쉬운 방법은 pip를 사용하는 것입니다.
Python pip install pandas
또는 다음에서 다운로드하세요. 여기 .
2. Pandas에서 DataFrame 만들기
에이 데이터프레임 행과 열에 데이터가 저장된 Pandas의 테이블과 같은 데이터 구조입니다. DataFrame은 여러 Python 시리즈 객체를 전달하여 생성할 수 있습니다. DataFrame 수업 ( pd.데이터프레임() )를 사용하여 pd.Series 방법. 이 예에서는 두 개의 Series 객체가 사용됩니다. s1 첫 번째 행과 s2 두 번째 행으로.
예 1: 시리즈에서 DataFrame 생성:
Python
import pandas as pd # Creating two Series: s1 (numbers) and s2 (names) s1 = pd . Series ([ 1 2 ]) s2 = pd . Series ([ 'Ashish' 'Sid' ]) # Creating DataFrame by combining Series as rows dataframe = pd . DataFrame ([ s1 s2 ]) # Displaying the DataFrame print ( dataframe )
산출:
예 2: 사용자 정의 인덱스 및 열 이름이 있는 목록의 DataFrame:
Python dataframe1 = pd . DataFrame ([[ 1 2 ] [ 'Ashish' 'Sid' ]] index = [ 'r1' 'r2' ] columns = [ 'c1' 'c2' ]) print ( dataframe1 )
산출:
예 3: 사전의 DataFrame:
Python dataframe2 = pd . DataFrame ({ 'c1' : [ 1 'Ashish' ] 'c2' : [ 2 'Sid' ] }) print ( dataframe2 )
산출:
3. Pandas로 데이터 가져오기
첫 번째 단계는 데이터를 읽는 것입니다. 우리의 경우 데이터는 각 행이 새 줄로 구분되고 각 열이 쉼표로 구분되는 CSV(쉼표로 구분된 값) 파일로 저장됩니다. Python에서 데이터를 사용하려면 csv를 읽어야 합니다. 파일 Pandas DataFrame에 넣습니다.
Python import pandas as pd # Read Country-data.csv into a DataFrame df = pd . read_csv ( 'Country-data.csv' ) # Prints the first 5 rows of a DataFrame as default df . head () # Prints no. of rows and columns of a DataFrame df . shape
산출:
(167 10)4. Pandas로 DataFrame 인덱싱하기
Pandas는 강력한 인덱싱 기능을 제공합니다. 두 가지를 모두 사용하여 DataFrame을 인덱싱할 수 있습니다. 위치 기반 그리고 라벨 기반 행동 양식.
위치 기반 인덱싱(사용
Pythoniloc):# prints first 5 rows and every column which replicates df.head() df . iloc [ 0 : 5 :] # prints entire rows and columns df . iloc [::] # prints from 5th rows and first 5 columns df . iloc [ 5 :: 5 ]산출:
![]()
![]()
![]()
레이블 기반 색인화(사용
loc):인덱싱은 다음을 사용하여 레이블로 작업할 수 있습니다. 팬더.DataFrame.loc 위치 대신 레이블을 사용하여 색인을 생성할 수 있는 방법입니다.
예:
Python# prints first five rows including 5th index and every columns of df df . loc [ 0 : 5 :] # prints from 5th rows onwards and entire columns df . loc [ 5 ::]산출:
![]()
![]()
위의 내용은 실제로 df.iloc[0:5:]와 크게 다르지 않습니다. 이는 행 레이블이 모든 값을 가질 수 있지만 행 레이블은 위치와 정확히 일치하기 때문입니다. 그러나 열 레이블을 사용하면 데이터 작업 시 작업이 훨씬 쉬워집니다.예:
Python# Prints the first 5 rows of Time period # value df . loc [: 5 'child_mort' ]산출:
![]()
5. Pandas를 사용한 DataFrame 수학
Pandas를 사용하면 데이터프레임에 저장된 데이터에 대한 수학적 연산을 더 쉽게 수행할 수 있습니다. 팬더에서 수행할 수 있는 작업은 벡터화되어 있어 빠르고 루프를 사용하지 않고도 모든 요소에 자동으로 적용됩니다.
예 - 열별 수학:
Python# Adding 5 to every element in column A df [ 'child_mort' ] = df [ 'child_mort' ] + 5 # Multiplying values in column B by 10 df [ 'exports' ] = df [ 'exports' ] * 10 df산출:
![]()
Pandas의 통계 함수:
팬더 도구의 통계 기능을 사용하여 데이터 프레임 계산을 수행할 수 있습니다. 다음과 같은 기능을 사용할 수 있습니다.
-
df.sum()→ 값의 합 -
df.mean()→ 평균 -
df.max()/df.min()→ 최대값과 최소값 -
df.describe()→ 빠른 통계 요약
# computes various summary statistics excluding NaN values df . describe () # Provides sum of all the values for each column df . sum ()
산출:
6. Pandas와 Matplotlib를 사용한 데이터 시각화
Pandas는 사용하기가 매우 쉽습니다. Matplotlib 기본 플롯과 차트를 만드는 데 사용되는 강력한 라이브러리입니다. 단 몇 줄의 코드만으로 데이터를 시각화하고 더 잘 이해할 수 있습니다. 다음은 Pandas 및 Matplotlib를 사용하여 플로팅을 시작하는 데 도움이 되는 몇 가지 간단한 예입니다.
Python # Import the library first import matplotlib.pyplot as plt
히스토그램
히스토그램은 열의 값 분포를 보여줍니다.
Python df [ 'income' ] . hist ( bins = 10 ) plt . title ( 'Histogram of Income' ) plt . xlabel ( 'Income Value' ) plt . ylabel ( 'Frequency' ) plt . show ()
산출:
박스 플롯
에이 상자 그림 이상값을 감지하고 데이터 확산을 이해하는 데 유용합니다.
Python df = df . head ( 10 ) plt . figure ( figsize = ( 20 6 )) # Increase width to make x-axis labels clearer df . boxplot ( column = 'imports' by = 'country' ) plt . title ( 'Boxplot by Country' ) plt . suptitle ( '' ) # Removes default title plt . xlabel ( 'Country' ) plt . ylabel ( 'Imports' ) plt . xticks ( rotation = 45 ) # Optional: Rotate x-axis labels for better visibility plt . tight_layout () # Adjust layout to avoid clipping plt . show ()
산출:
산점도
에이 산점도 두 변수 사이의 관계를 보여줍니다.
Python x = df [ 'health' ] y = df [ 'life_expec' ] plt . scatter ( x y label = 'Data Points' color = 'm' marker = '*' s = 30 ) plt . xlabel ( 'Health' ) plt . ylabel ( 'Life Expectancy' ) plt . title ( 'Scatter Plot of Health vs Life Expectancy' ) plt . legend () plt . show ()
산출:
관련 기사:
- 팬더 소개
- Python의 그래프 플로팅
- Python에서 csv 파일 작업
- 팬더 데이터프레임
- Matplotlib 소개
- 히스토그램 - 정의 유형 그래프 및 예
- 박스 플롯
- 산점도