<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>data_lover.log</title>
        <link>https://velog.io/</link>
        <description>print("I_can_")</description>
        <lastBuildDate>Thu, 13 Mar 2025 07:38:55 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <image>
            <title>data_lover.log</title>
            <url>https://velog.velcdn.com/images/data_lover/profile/3fddf383-7c1a-4e73-869d-11ce466d1599/image.png</url>
            <link>https://velog.io/</link>
        </image>
        <copyright>Copyright (C) 2019. data_lover.log. All rights reserved.</copyright>
        <atom:link href="https://v2.velog.io/rss/data_lover" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[Visualization3]]></title>
            <link>https://velog.io/@data_lover/Visualization3-dcf327hv</link>
            <guid>https://velog.io/@data_lover/Visualization3-dcf327hv</guid>
            <pubDate>Thu, 13 Mar 2025 07:38:55 GMT</pubDate>
            <description><![CDATA[<h1 id="seaborn-시각화-라이브러리">Seaborn 시각화 라이브러리</h1>
<p>Seaborn은 Matplotlib을 기반으로 한 고급 시각화 라이브러리로, 통계적 그래프를 쉽게 생성할 수 있도록 설계됨. 기본적으로 데이터프레임과 잘 연동되며, 다양한 스타일과 색상 테마를 제공함.</p>
<h2 id="1-seaborn-기본-설정">1. Seaborn 기본 설정</h2>
<p>Seaborn을 사용하기 위해 먼저 라이브러리를 불러오고, 기본 스타일을 설정할 수 있음.</p>
<pre><code class="language-python">import seaborn as sns
import matplotlib.pyplot as plt

# Seaborn 스타일 설정
sns.set_style(&quot;whitegrid&quot;)  # 스타일 변경 가능: &quot;darkgrid&quot;, &quot;white&quot;, &quot;ticks&quot; 등

# 샘플 데이터 로드
df = sns.load_dataset(&quot;tips&quot;)  # Seaborn 제공 예제 데이터셋
</code></pre>
<h2 id="2-주요-그래프-유형">2. 주요 그래프 유형</h2>
<h3 id="●-분포-시각화-distribution-plots">● 분포 시각화 (Distribution Plots)</h3>
<ul>
<li>히스토그램(histogram)과 KDE(Kernel Density Estimation)를 사용하여 데이터의 분포를 시각화할 수 있음.</li>
<li><code>bins</code> 옵션을 사용하여 막대의 개수를 조절할 수 있으며, <code>kde=True</code>를 설정하면 밀도 그래프도 함께 표시됨.</li>
</ul>
<h3 id="히스토그램-histogram">히스토그램 (Histogram)</h3>
<pre><code class="language-python">import numpy as np
np.random.seed(42)
data = np.random.randn(1000)  # 정규 분포를 따르는 랜덤 데이터 생성

# 히스토그램 &amp; KDE
sns.histplot(data, bins=30, kde=True, color=&#39;blue&#39;)
plt.title(&quot;Histogram with KDE&quot;)
plt.xlabel(&quot;Value&quot;)
plt.ylabel(&quot;Frequency&quot;)
plt.show()
</code></pre>
<h3 id="커널-밀도-추정kde-그래프">커널 밀도 추정(KDE) 그래프</h3>
<pre><code class="language-python">sns.kdeplot(data, shade=True, color=&#39;red&#39;)
plt.title(&quot;Kernel Density Estimation (KDE) Plot&quot;)
plt.xlabel(&quot;Value&quot;)
plt.ylabel(&quot;Density&quot;)
plt.show()
</code></pre>
<h3 id="●-관계-시각화-relational-plots">● 관계 시각화 (Relational Plots)</h3>
<ul>
<li>두 변수 간 관계를 표현하는 그래프</li>
<li><code>scatterplot()</code>은 산점도를 그리며, <code>lineplot()</code>은 선 그래프를 그림.</li>
</ul>
<h3 id="산점도-scatter-plot">산점도 (Scatter Plot)</h3>
<pre><code class="language-python"># 산점도를 활용하여 total_bill과 tip의 관계를 시각화
sns.scatterplot(data=df, x=&quot;total_bill&quot;, y=&quot;tip&quot;, hue=&quot;sex&quot;, style=&quot;sex&quot;)
plt.title(&quot;Scatter Plot of Total Bill vs. Tip&quot;)
plt.xlabel(&quot;Total Bill ($)&quot;)
plt.ylabel(&quot;Tip ($)&quot;)
plt.show()
</code></pre>
<h3 id="선-그래프-line-plot">선 그래프 (Line Plot)</h3>
<pre><code class="language-python"># total_bill의 평균값을 선 그래프로 표현
sns.lineplot(data=df, x=&quot;size&quot;, y=&quot;total_bill&quot;, ci=None)
plt.title(&quot;Line Plot of Total Bill by Party Size&quot;)
plt.xlabel(&quot;Party Size&quot;)
plt.ylabel(&quot;Total Bill ($)&quot;)
plt.show()
</code></pre>
<h3 id="●-범주형-데이터-시각화-categorical-plots">● 범주형 데이터 시각화 (Categorical Plots)</h3>
<ul>
<li><code>barplot()</code>, <code>boxplot()</code>, <code>violinplot()</code> 등 범주형 변수에 대한 다양한 시각화 제공</li>
</ul>
<h3 id="박스-플롯-box-plot">박스 플롯 (Box Plot)</h3>
<pre><code class="language-python">sns.boxplot(data=df, x=&quot;day&quot;, y=&quot;total_bill&quot;, hue=&quot;sex&quot;)
plt.title(&quot;Box Plot of Total Bill by Day&quot;)
plt.xlabel(&quot;Day of the Week&quot;)
plt.ylabel(&quot;Total Bill ($)&quot;)
plt.legend(title=&quot;Sex&quot;)
plt.show()
</code></pre>
<h3 id="바이올린-플롯-violin-plot">바이올린 플롯 (Violin Plot)</h3>
<pre><code class="language-python">sns.violinplot(data=df, x=&quot;day&quot;, y=&quot;total_bill&quot;, hue=&quot;sex&quot;, split=True)
plt.title(&quot;Violin Plot of Total Bill by Day&quot;)
plt.xlabel(&quot;Day of the Week&quot;)
plt.ylabel(&quot;Total Bill ($)&quot;)
plt.legend(title=&quot;Sex&quot;)
plt.show()
</code></pre>
<h3 id="●-행렬-시각화-matrix-plots">● 행렬 시각화 (Matrix Plots)</h3>
<ul>
<li><code>heatmap()</code>을 이용하여 데이터의 상관관계 또는 특정 행렬 데이터를 시각화 가능</li>
<li><code>annot=True</code> 옵션을 사용하면 값이 표시됨.</li>
</ul>
<h3 id="히트맵-heatmap">히트맵 (Heatmap)</h3>
<pre><code class="language-python"># 상관행렬 계산
corr = df.corr()

# 히트맵 생성
sns.heatmap(corr, annot=True, cmap=&quot;coolwarm&quot;, fmt=&quot;.2f&quot;)
plt.title(&quot;Heatmap of Correlation Matrix&quot;)
plt.show()
</code></pre>
<h3 id="●-다변수-시각화-multivariate-visualization">● 다변수 시각화 (Multivariate Visualization)</h3>
<ul>
<li>여러 변수 간 관계를 한 번에 표현할 수 있는 <code>pairplot()</code>과 <code>FacetGrid()</code> 제공</li>
</ul>
<h3 id="페어플롯-pairplot">페어플롯 (Pairplot)</h3>
<pre><code class="language-python">sns.pairplot(df, hue=&quot;sex&quot;, diag_kind=&quot;kde&quot;)
plt.show()
</code></pre>
<h3 id="페이싯-그리드-facetgrid">페이싯 그리드 (FacetGrid)</h3>
<pre><code class="language-python">g = sns.FacetGrid(df, col=&quot;sex&quot;, row=&quot;time&quot;, margin_titles=True)
g.map_dataframe(sns.scatterplot, x=&quot;total_bill&quot;, y=&quot;tip&quot;)
g.set_axis_labels(&quot;Total Bill ($)&quot;, &quot;Tip ($)&quot;)
plt.show()
</code></pre>
<h2 id="3-seaborn-고급-기능">3. Seaborn 고급 기능</h2>
<h3 id="●-스타일과-색상-조정">● 스타일과 색상 조정</h3>
<p>Seaborn은 다양한 스타일과 색상 테마를 제공하여 시각화를 더욱 미적으로 만들 수 있음.</p>
<pre><code class="language-python">sns.set_style(&quot;darkgrid&quot;)  # 스타일 변경 가능: &quot;whitegrid&quot;, &quot;dark&quot;, &quot;white&quot;, &quot;ticks&quot;
sns.set_palette(&quot;pastel&quot;)  # 색상 테마 설정 가능: &quot;deep&quot;, &quot;muted&quot;, &quot;bright&quot;, &quot;pastel&quot;, &quot;dark&quot;
</code></pre>
<h3 id="●-범례-및-제목-설정">● 범례 및 제목 설정</h3>
<p>그래프의 제목과 범례를 추가하여 가독성을 높일 수 있음.</p>
<pre><code class="language-python">ax = sns.scatterplot(data=df, x=&quot;total_bill&quot;, y=&quot;tip&quot;, hue=&quot;sex&quot;, style=&quot;sex&quot;)
ax.set_title(&quot;Total Bill vs. Tip by Gender&quot;)
ax.legend(title=&quot;Gender&quot;)
plt.xlabel(&quot;Total Bill ($)&quot;)
plt.ylabel(&quot;Tip ($)&quot;)
plt.show()
</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[Visualization2]]></title>
            <link>https://velog.io/@data_lover/Visualization2</link>
            <guid>https://velog.io/@data_lover/Visualization2</guid>
            <pubDate>Thu, 13 Mar 2025 07:33:50 GMT</pubDate>
            <description><![CDATA[<h1 id="판다스-시각화-도구">판다스 시각화 도구</h1>
<p>판다스는 <code>matplotlib</code>과 연동하여 데이터를 쉽게 시각화할 수 있는 기능을 제공함. <code>plot()</code> 메서드를 사용하여 다양한 그래프를 그릴 수 있으며, 데이터의 유형에 따라 적절한 그래프를 선택하여 시각화를 수행함.</p>
<h2 id="1-시리즈series-시각화">1. 시리즈(Series) 시각화</h2>
<p>시리즈(Series)는 1차원 데이터 구조로, 시간에 따른 값의 변화나 특정 변수의 값을 표현하는 데 유용함.</p>
<h3 id="●-선-그래프-line-plot">● 선 그래프 (Line Plot)</h3>
<ul>
<li><code>Series.plot()</code>을 사용하여 간단한 선 그래프를 그릴 수 있음.</li>
<li>기본적으로 x축은 인덱스, y축은 값이 됨.</li>
<li><code>marker</code> 옵션을 추가하여 점을 강조할 수도 있음.</li>
</ul>
<pre><code class="language-python">import pandas as pd
import matplotlib.pyplot as plt

s = pd.Series([1, 3, 2, 5, 7, 8], index=[&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;])
s.plot(marker=&#39;o&#39;, linestyle=&#39;-&#39;)
plt.title(&quot;Series Line Plot&quot;)  # 그래프 제목 추가
plt.xlabel(&quot;Index&quot;)  # x축 라벨
plt.ylabel(&quot;Values&quot;)  # y축 라벨
plt.grid(True)  # 격자 추가
plt.show()</code></pre>
<h3 id="●-막대-그래프-bar-plot">● 막대 그래프 (Bar Plot)</h3>
<ul>
<li><code>kind=&#39;bar&#39;</code> 옵션을 사용하여 막대 그래프를 생성할 수 있음.</li>
<li>색상을 지정할 수 있으며, <code>rot</code> 옵션을 사용하여 x축 라벨 회전 가능.</li>
</ul>
<pre><code class="language-python">s.plot(kind=&#39;bar&#39;, color=&#39;skyblue&#39;, rot=0)
plt.title(&quot;Series Bar Plot&quot;)
plt.xlabel(&quot;Categories&quot;)
plt.ylabel(&quot;Values&quot;)
plt.show()</code></pre>
<h2 id="2-데이터프레임dataframe-시각화">2. 데이터프레임(DataFrame) 시각화</h2>
<p>데이터프레임(DataFrame)은 2차원 데이터 구조로 여러 개의 열(column)과 행(row)으로 구성됨. 여러 변수의 값을 비교할 때 사용됨.</p>
<h3 id="●-선-그래프-line-plot-1">● 선 그래프 (Line Plot)</h3>
<ul>
<li>여러 열을 한 번에 선 그래프로 나타낼 수 있음.</li>
<li>스타일을 변경하여 선 모양을 조정 가능.</li>
</ul>
<pre><code class="language-python">df = pd.DataFrame({
    &#39;A&#39;: [1, 3, 2, 4],
    &#39;B&#39;: [2, 4, 5, 7]
}, index=[&#39;Q1&#39;, &#39;Q2&#39;, &#39;Q3&#39;, &#39;Q4&#39;])

df.plot(marker=&#39;o&#39;, linestyle=&#39;-&#39;)
plt.title(&quot;DataFrame Line Plot&quot;)
plt.xlabel(&quot;Quarter&quot;)
plt.ylabel(&quot;Values&quot;)
plt.grid(True)
plt.show()</code></pre>
<h3 id="●-막대-그래프-bar-plot-1">● 막대 그래프 (Bar Plot)</h3>
<ul>
<li>데이터프레임에서도 <code>kind=&#39;bar&#39;</code> 옵션을 사용하여 막대 그래프를 만들 수 있음.</li>
</ul>
<pre><code class="language-python">df.plot(kind=&#39;bar&#39;, color=[&#39;blue&#39;, &#39;orange&#39;])
plt.title(&quot;DataFrame Bar Plot&quot;)
plt.xlabel(&quot;Quarter&quot;)
plt.ylabel(&quot;Values&quot;)
plt.legend(title=&quot;Categories&quot;)
plt.show()</code></pre>
<h3 id="●-누적-막대-그래프-stacked-bar-plot">● 누적 막대 그래프 (Stacked Bar Plot)</h3>
<ul>
<li><code>stacked=True</code> 옵션을 사용하여 누적 막대 그래프를 생성할 수 있음.</li>
</ul>
<pre><code class="language-python">df.plot(kind=&#39;bar&#39;, stacked=True, color=[&#39;blue&#39;, &#39;orange&#39;])
plt.title(&quot;Stacked Bar Plot&quot;)
plt.xlabel(&quot;Quarter&quot;)
plt.ylabel(&quot;Total Values&quot;)
plt.legend(title=&quot;Categories&quot;)
plt.show()</code></pre>
<h3 id="●-그래프-스타일-변환">● 그래프 스타일 변환</h3>
<ul>
<li><code>style</code> 옵션을 활용하여 선 스타일을 변경할 수 있음.</li>
<li><code>&#39;-&#39;</code>, <code>&#39;--&#39;</code>, <code>&#39;:&#39;</code>, <code>&#39;-.&#39;</code> 등의 스타일을 조합할 수 있음.</li>
</ul>
<pre><code class="language-python">df.plot(style=[&#39;--&#39;, &#39;o-&#39;])
plt.title(&quot;Styled Line Plot&quot;)
plt.xlabel(&quot;Quarter&quot;)
plt.ylabel(&quot;Values&quot;)
plt.grid(True)
plt.show()</code></pre>
<h3 id="●-히스토그램-histogram">● 히스토그램 (Histogram)</h3>
<ul>
<li>연속형 데이터의 분포를 확인하는 데 유용함.</li>
<li><code>bins</code> 옵션을 통해 구간 개수를 조정할 수 있음.</li>
</ul>
<pre><code class="language-python">df.hist(bins=5, color=&#39;lightblue&#39;, edgecolor=&#39;black&#39;)
plt.title(&quot;Histogram Plot&quot;)
plt.xlabel(&quot;Value Ranges&quot;)
plt.ylabel(&quot;Frequency&quot;)
plt.show()</code></pre>
<h3 id="●-산점도-scatter-plot">● 산점도 (Scatter Plot)</h3>
<ul>
<li>두 개의 변수 간 관계를 나타낼 때 사용.</li>
</ul>
<pre><code class="language-python">df.plot(kind=&#39;scatter&#39;, x=&#39;A&#39;, y=&#39;B&#39;, color=&#39;red&#39;)
plt.title(&quot;Scatter Plot&quot;)
plt.xlabel(&quot;A Values&quot;)
plt.ylabel(&quot;B Values&quot;)
plt.show()</code></pre>
<h2 id="3-주석-추가-annotations">3. 주석 추가 (Annotations)</h2>
<ul>
<li><code>plt.text()</code>를 사용하여 그래프 위에 주석을 추가할 수 있음.</li>
<li><code>arrowprops</code>를 사용하면 화살표 표시 가능.</li>
</ul>
<pre><code class="language-python">ax = df.plot(marker=&#39;o&#39;)
plt.text(1, 3, &#39;Peak Point&#39;, fontsize=12, color=&#39;red&#39;)  # (x, y) 위치에 텍스트 추가
plt.annotate(&#39;Max Value&#39;, xy=(3, 7), xytext=(2, 6), 
             arrowprops=dict(facecolor=&#39;black&#39;, arrowstyle=&#39;-&gt;&#39;))  # 화살표 추가
plt.show()</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[Visualization]]></title>
            <link>https://velog.io/@data_lover/Visualization</link>
            <guid>https://velog.io/@data_lover/Visualization</guid>
            <pubDate>Thu, 13 Mar 2025 07:28:18 GMT</pubDate>
            <description><![CDATA[<h1 id="matplotlibpyplot">matplotlib.pyplot</h1>
<h2 id="1-matplotlibpyplot">1. <code>matplotlib.pyplot</code></h2>
<ul>
<li><code>matplotlib.pyplot</code>은 파이썬에서 그래프를 그릴 때 사용하는 가장 기본적인 라이브러리 중 하나임.</li>
<li>MATLAB의 <code>plot()</code> 함수와 유사하게 작동하며, 간단한 명령어로 다양한 시각화를 구현할 수 있음.</li>
<li>그래프를 그리는 기본적인 흐름은 다음과 같음:<ol>
<li><code>import matplotlib.pyplot as plt</code>로 라이브러리를 불러오기</li>
<li>데이터를 준비하기</li>
<li><code>plt.plot()</code> 등의 함수를 이용해 그래프를 생성하기</li>
<li><code>plt.show()</code>를 이용해 그래프를 화면에 출력하기</li>
</ol>
</li>
</ul>
<pre><code class="language-python">import matplotlib.pyplot as plt
</code></pre>
<hr>
<h2 id="2-기본적인-그래프-그리기">2. 기본적인 그래프 그리기</h2>
<ul>
<li>가장 기본적인 라인 플롯(line plot) 그리는 방법</li>
</ul>
<pre><code class="language-python">import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]  # x축 값
y = [10, 20, 25, 30, 50]  # y축 값

plt.plot(x, y)  # x축과 y축 데이터를 연결하여 그래프 생성
plt.show()  # 그래프 출력
</code></pre>
<ul>
<li><code>plt.plot(x, y)</code>: x축과 y축 데이터를 연결하여 선 그래프를 그림.</li>
<li><code>plt.show()</code>: 생성된 그래프를 화면에 표시.</li>
</ul>
<blockquote>
<p>위 코드를 실행하면 x축 값 [1, 2, 3, 4, 5]와 y축 값 [10, 20, 25, 30, 50]을 가진 선 그래프가 출력됨.</p>
</blockquote>
<hr>
<h2 id="3-그래프-제목-축-레이블-범례-추가하기">3. 그래프 제목, 축 레이블, 범례 추가하기</h2>
<ul>
<li>그래프의 가독성을 높이기 위해 제목, 축 레이블, 범례를 추가할 수 있음.</li>
</ul>
<pre><code class="language-python">plt.plot(x, y, label=&#39;Line Graph&#39;)  # 그래프에 라벨 추가
plt.xlabel(&#39;X 축&#39;)  # X축 이름
plt.ylabel(&#39;Y 축&#39;)  # Y축 이름
plt.title(&#39;기본 그래프&#39;)  # 그래프 제목
plt.legend()  # 범례 표시
plt.show()
</code></pre>
<ul>
<li><code>plt.xlabel()</code>, <code>plt.ylabel()</code>: x축과 y축에 설명을 추가.</li>
<li><code>plt.title()</code>: 그래프 제목을 설정.</li>
<li><code>plt.legend()</code>: 그래프의 라벨을 표시하여 범례를 추가.</li>
</ul>
<hr>
<h2 id="4-마커marker와-선-스타일-변경하기">4. 마커(marker)와 선 스타일 변경하기</h2>
<pre><code class="language-python">plt.plot(x, y, marker=&#39;o&#39;, linestyle=&#39;--&#39;, color=&#39;r&#39;, label=&#39;데이터&#39;)
plt.legend()
plt.show()
</code></pre>
<ul>
<li><code>marker=&#39;o&#39;</code>: 데이터 포인트를 동그라미로 표시.</li>
<li><code>linestyle=&#39;--&#39;</code>: 점선 스타일 적용.</li>
<li><code>color=&#39;r&#39;</code>: 선의 색상을 빨간색으로 지정.</li>
</ul>
<blockquote>
<p>이 코드를 실행하면 점선 스타일의 빨간색 그래프가 출력되며, 데이터 포인트는 동그라미로 표시됨.</p>
</blockquote>
<hr>
<h2 id="5-여러-개의-그래프-그리기">5. 여러 개의 그래프 그리기</h2>
<ul>
<li>한 개의 그래프에서 여러 개의 선을 그릴 수도 있음.</li>
</ul>
<pre><code class="language-python">x2 = [1, 2, 3, 4, 5]
y2 = [5, 15, 20, 25, 35]

plt.plot(x, y, label=&#39;라인1&#39;, color=&#39;blue&#39;)
plt.plot(x2, y2, label=&#39;라인2&#39;, color=&#39;green&#39;)
plt.legend()
plt.show()
</code></pre>
<ul>
<li><code>plt.plot()</code>을 여러 번 사용하면 한 그래프에 여러 개의 선을 표시할 수 있음.</li>
<li>각각의 <code>label</code>을 다르게 지정하여 범례를 활용 가능.</li>
</ul>
<hr>
<h2 id="6-바-그래프-bar-chart">6. 바 그래프 (Bar Chart)</h2>
<pre><code class="language-python">categories = [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;]
values = [10, 20, 15, 25]

plt.bar(categories, values, color=&#39;purple&#39;)
plt.xlabel(&#39;카테고리&#39;)
plt.ylabel(&#39;값&#39;)
plt.title(&#39;바 그래프&#39;)
plt.show()
</code></pre>
<ul>
<li><code>plt.bar()</code>를 사용하여 바 그래프를 생성.</li>
<li>카테고리별 데이터를 시각적으로 비교할 때 유용함.</li>
</ul>
<hr>
<h2 id="7-히스토그램-histogram">7. 히스토그램 (Histogram)</h2>
<pre><code class="language-python">import numpy as np

# 난수 생성
np.random.seed(42)
data = np.random.randn(1000)

plt.hist(data, bins=30, color=&#39;skyblue&#39;, edgecolor=&#39;black&#39;)
plt.xlabel(&#39;값&#39;)
plt.ylabel(&#39;빈도&#39;)
plt.title(&#39;히스토그램&#39;)
plt.show()
</code></pre>
<ul>
<li><code>plt.hist()</code>: 데이터의 분포를 나타내는 히스토그램을 생성.</li>
<li><code>bins=30</code>: 30개의 구간으로 나누어 표현.</li>
<li><code>color=&#39;skyblue&#39;</code>, <code>edgecolor=&#39;black&#39;</code>: 막대의 색상을 설정.</li>
</ul>
<hr>
<h2 id="8-산점도-scatter-plot">8. 산점도 (Scatter Plot)</h2>
<pre><code class="language-python">x = np.random.rand(50)
y = np.random.rand(50)

plt.scatter(x, y, color=&#39;red&#39;)
plt.xlabel(&#39;X 값&#39;)
plt.ylabel(&#39;Y 값&#39;)
plt.title(&#39;산점도&#39;)
plt.show()
</code></pre>
<ul>
<li><code>plt.scatter()</code>: 개별 데이터 포인트를 표시하는 산점도를 그림.</li>
<li>데이터 간의 관계를 시각화할 때 유용함.</li>
</ul>
<hr>
<h2 id="9-파이-차트-pie-chart">9. 파이 차트 (Pie Chart)</h2>
<pre><code class="language-python">labels = [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;]
sizes = [15, 30, 45, 10]
colors = [&#39;gold&#39;, &#39;yellowgreen&#39;, &#39;lightcoral&#39;, &#39;lightskyblue&#39;]

plt.pie(sizes, labels=labels, colors=colors, autopct=&#39;%1.1f%%&#39;, startangle=140)
plt.title(&#39;파이 차트&#39;)
plt.show()
</code></pre>
<ul>
<li><code>plt.pie()</code>: 원형 그래프를 생성하여 각 데이터 비율을 시각적으로 표현.</li>
<li><code>autopct=&#39;%1.1f%%&#39;</code>: 비율을 소수점 1자리까지 표시.</li>
</ul>
<hr>
<h2 id="10-서브플롯-subplot">10. 서브플롯 (Subplot)</h2>
<ul>
<li>여러 개의 그래프를 한 화면에 배치할 수 있음.</li>
</ul>
<pre><code class="language-python">fig, axs = plt.subplots(2, 2, figsize=(10, 10))

axs[0, 0].plot(x, y, color=&#39;blue&#39;)
axs[0, 0].set_title(&#39;라인 플롯&#39;)

axs[0, 1].bar(categories, values, color=&#39;purple&#39;)
axs[0, 1].set_title(&#39;바 그래프&#39;)

axs[1, 0].scatter(x, y, color=&#39;red&#39;)
axs[1, 0].set_title(&#39;산점도&#39;)

axs[1, 1].hist(data, bins=30, color=&#39;skyblue&#39;)
axs[1, 1].set_title(&#39;히스토그램&#39;)

plt.tight_layout()
plt.show()
</code></pre>
<blockquote>
<p>plt.subplots()를 활용하면 여러 개의 그래프를 한 화면에 구성할 수 있음.</p>
</blockquote>
]]></description>
        </item>
        <item>
            <title><![CDATA[Pandas7_2]]></title>
            <link>https://velog.io/@data_lover/Pandas72</link>
            <guid>https://velog.io/@data_lover/Pandas72</guid>
            <pubDate>Thu, 13 Mar 2025 07:20:10 GMT</pubDate>
            <description><![CDATA[<h1 id="데이터-집계">데이터 집계</h1>
<h2 id="1-집계-함수-그룹화-집계-메소드">1. 집계 함수 (그룹화 집계 메소드)</h2>
<ul>
<li>그룹화된 데이터에서 다양한 통계량을 계산할 때 사용됨.</li>
<li>대표적인 집계 함수들은 아래와 같음.</li>
</ul>
<table>
<thead>
<tr>
<th>메소드</th>
<th>설명</th>
</tr>
</thead>
<tbody><tr>
<td><code>.sum()</code></td>
<td>그룹별 합계</td>
</tr>
<tr>
<td><code>.mean()</code></td>
<td>그룹별 평균</td>
</tr>
<tr>
<td><code>.median()</code></td>
<td>그룹별 중앙값</td>
</tr>
<tr>
<td><code>.min()</code></td>
<td>그룹별 최소값</td>
</tr>
<tr>
<td><code>.max()</code></td>
<td>그룹별 최대값</td>
</tr>
<tr>
<td><code>.count()</code></td>
<td>그룹별 개수</td>
</tr>
<tr>
<td><code>.std()</code></td>
<td>그룹별 표준편차</td>
</tr>
<tr>
<td><code>.var()</code></td>
<td>그룹별 분산</td>
</tr>
<tr>
<td><code>.first()</code></td>
<td>그룹별 첫 번째 값</td>
</tr>
<tr>
<td><code>.last()</code></td>
<td>그룹별 마지막 값</td>
</tr>
</tbody></table>
<pre><code class="language-python">import pandas as pd

df = pd.DataFrame({&#39;A&#39;: [&#39;foo&#39;, &#39;foo&#39;, &#39;bar&#39;, &#39;bar&#39;],
                   &#39;B&#39;: [1, 2, 3, 4]})

grouped = df.groupby(&#39;A&#39;).sum()
print(grouped)
# 출력
#        B
# A
# bar    7
# foo    3
</code></pre>
<hr>
<h2 id="2-사용자-정의-집계-함수">2. 사용자 정의 집계 함수</h2>
<ul>
<li>기본 제공 집계 함수 외에도 사용자가 직접 함수를 정의하여 적용 가능함.</li>
<li><code>agg()</code> 또는 <code>apply()</code>를 활용하여 특정 연산 수행 가능함.</li>
</ul>
<pre><code class="language-python">def custom_function(x):
    return x.max() - x.min()

grouped = df.groupby(&#39;A&#39;)[&#39;B&#39;].agg(custom_function)
print(grouped)
# 출력
# A
# bar    1
# foo    1
</code></pre>
<hr>
<h2 id="3-비집계-함수">3. 비집계 함수</h2>
<ul>
<li>데이터 변환에 사용되는 함수로, 그룹별 특정 연산을 수행하지만 전체를 하나의 값으로 줄이지 않음.</li>
<li><code>.transform()</code>을 사용하면 원래 데이터의 형태를 유지하면서 그룹별 연산을 적용 가능함.</li>
</ul>
<pre><code class="language-python">df[&#39;B_normalized&#39;] = df.groupby(&#39;A&#39;)[&#39;B&#39;].transform(lambda x: (x - x.mean()) / x.std())
print(df)
# 출력
#      A  B  B_normalized
# 0  foo  1          -1.0
# 1  foo  2           1.0
# 2  bar  3          -1.0
# 3  bar  4           1.0
</code></pre>
<hr>
<h2 id="4-열별로-여러-함수-적용하기">4. 열별로 여러 함수 적용하기</h2>
<ul>
<li>여러 개의 집계 함수를 한 번에 적용할 수 있음.</li>
</ul>
<pre><code class="language-python">df.groupby(&#39;A&#39;).agg({&#39;B&#39;: [&#39;sum&#39;, &#39;mean&#39;, &#39;std&#39;]})
# 출력
#          B
#        sum mean  std
# A
# bar     7  3.5  0.7071
# foo     3  1.5  0.7071
</code></pre>
<hr>
<h2 id="5-apply---다목적-데이터-집계">5. <code>apply()</code> - 다목적 데이터 집계</h2>
<ul>
<li>그룹화 후 특정 연산을 수행하여 데이터 변환이 가능함.</li>
</ul>
<pre><code class="language-python">df.groupby(&#39;A&#39;).apply(lambda x: x.sort_values(&#39;B&#39;, ascending=False))
</code></pre>
<hr>
<h2 id="6-그룹키-제거">6. 그룹키 제거</h2>
<ul>
<li><code>group_keys=False</code> 옵션을 주면 그룹화된 데이터에서 키를 제거하고 원래 형태를 유지할 수 있음.</li>
</ul>
<pre><code class="language-python">df.groupby(&#39;A&#39;, group_keys=False).apply(lambda x: x.head(1))
</code></pre>
<hr>
<h2 id="7-분위와-구간-분석">7. 분위와 구간 분석</h2>
<ul>
<li><code>qcut()</code>을 사용하여 데이터를 분위수 기준으로 나눌 수 있음.</li>
</ul>
<pre><code class="language-python">df[&#39;quantile&#39;] = pd.qcut(df[&#39;B&#39;], q=4)
print(df)
</code></pre>
<hr>
<h2 id="8-그룹별-결측치-채우기">8. 그룹별 결측치 채우기</h2>
<ul>
<li>그룹별 평균값으로 결측치를 채울 수 있음.</li>
</ul>
<pre><code class="language-python">df.groupby(&#39;A&#39;).apply(lambda x: x.fillna(x.mean()))
</code></pre>
<hr>
<h2 id="9-무작위-샘플링">9. 무작위 샘플링</h2>
<ul>
<li><code>sample()</code>을 사용하여 그룹별 샘플을 선택할 수 있음.</li>
</ul>
<pre><code class="language-python">df.groupby(&#39;A&#39;).apply(lambda x: x.sample(n=1))
</code></pre>
<hr>
<h2 id="10-그룹별-가중치-합">10. 그룹별 가중치 합</h2>
<ul>
<li>특정 열을 가중치로 사용하여 그룹별 합계를 계산할 수 있음.</li>
</ul>
<pre><code class="language-python">df.groupby(&#39;A&#39;).apply(lambda x: (x[&#39;B&#39;] * x[&#39;B&#39;]).sum())
</code></pre>
<hr>
<h2 id="11-그룹-단위-선형회귀">11. 그룹 단위 선형회귀</h2>
<ul>
<li>그룹별로 선형회귀를 수행할 수 있음.</li>
</ul>
<pre><code class="language-python">from sklearn.linear_model import LinearRegression

def lin_reg(df):
    model = LinearRegression()
    X = df[[&#39;B&#39;]]
    y = df[&#39;B&#39;]
    model.fit(X, y)
    return model.coef_[0]

df.groupby(&#39;A&#39;).apply(lin_reg)
</code></pre>
<hr>
<h2 id="12-그룹-변환">12. 그룹 변환</h2>
<ul>
<li>그룹별 연산을 수행하면서 결과의 크기를 원래 데이터와 동일하게 유지할 수 있음.</li>
</ul>
<pre><code class="language-python">df.groupby(&#39;A&#39;)[&#39;B&#39;].transform(lambda x: x - x.mean())
</code></pre>
<hr>
<h2 id="13-피벗-테이블">13. 피벗 테이블</h2>
<ul>
<li>피벗 테이블을 사용하여 특정 그룹별 통계를 계산할 수 있음.</li>
</ul>
<pre><code class="language-python">pd.pivot_table(df, values=&#39;B&#39;, index=&#39;A&#39;, aggfunc=&#39;mean&#39;)
</code></pre>
<hr>
<h2 id="14-cross-tabulations-crosstab">14. Cross-Tabulations: <code>crosstab</code></h2>
<ul>
<li>교차 테이블을 사용하여 범주형 변수 간의 관계를 분석할 수 있음.</li>
</ul>
<pre><code class="language-python">pd.crosstab(df[&#39;A&#39;], df[&#39;B&#39;])
</code></pre>
<hr>
]]></description>
        </item>
        <item>
            <title><![CDATA[정규식]]></title>
            <link>https://velog.io/@data_lover/%EC%A0%95%EA%B7%9C%EC%8B%9D</link>
            <guid>https://velog.io/@data_lover/%EC%A0%95%EA%B7%9C%EC%8B%9D</guid>
            <pubDate>Wed, 12 Mar 2025 07:49:51 GMT</pubDate>
            <description><![CDATA[<h1 id="1-re-모듈이-필요한-이유">1. re 모듈이 필요한 이유</h1>
<p>1-1. 문자열 다루기에서 정규표현식이 중요한 이유</p>
<ul>
<li>일반적인 문자열 처리는 <code>split()</code>, <code>replace()</code> 같은 기본 함수로 해결할 수 있지만, 복잡한 패턴을 다룰 때는 코드가 길어지고 복잡해짐.</li>
<li>정규표현식(Regex)을 사용하면 짧고 간결한 코드로 패턴을 검색하고 수정할 수 있음.</li>
</ul>
<p>1-2. 예제 문제: 전화번호 가운데 자리 숨기기</p>
<pre><code class="language-python">import re

text = &#39;&#39;&#39;
Elice 123456-1234567 010-1234-5678
Cheshire 345678-678901 01098765432
&#39;&#39;&#39;

# 전화번호 패턴을 찾아 가운데 숫자를 &#39;*&#39;로 변경
masked_text = re.sub(r&#39;(\d{3,4})-(\d{4})-(\d{4})&#39;, r&#39;\1-****-\3&#39;, text)
print(masked_text)
</code></pre>
<ul>
<li><code>re.sub(pattern, replace, text)</code>: 특정 패턴을 찾아 변경하는 함수.</li>
<li><code>(\d{3,4})-(\d{4})-(\d{4})</code> → 전화번호 패턴을 정의 (3~4자리 숫자)-(4자리 숫자)-(4자리 숫자)</li>
<li><code>\1</code>, <code>\3</code> → 그룹핑을 활용해 첫 번째, 세 번째 그룹은 그대로 유지하고 두 번째 그룹만 <code>***</code>로 변경.</li>
</ul>
<hr>
<h1 id="2-메타-문자meta-characters">2. 메타 문자(Meta Characters)</h1>
<p>2-1. 메타 문자의 개념</p>
<ul>
<li>특정한 의미를 가지는 특수 기호로, 정규표현식을 구성하는 중요한 요소.</li>
<li>특정 패턴을 빠르게 찾을 수 있도록 도와줌.</li>
</ul>
<p>2-2. 주요 메타 문자</p>
<table>
<thead>
<tr>
<th>메타 문자</th>
<th>의미</th>
<th>예시</th>
</tr>
</thead>
<tbody><tr>
<td><code>^</code></td>
<td>문자열 시작</td>
<td><code>^www</code> → <code>www</code>로 시작하는 문자열 찾기</td>
</tr>
<tr>
<td><code>$</code></td>
<td>문자열 끝</td>
<td><code>.com$</code> → <code>.com</code>으로 끝나는 문자열 찾기</td>
</tr>
<tr>
<td>`</td>
<td>`</td>
<td>OR 조건</td>
</tr>
<tr>
<td><code>[]</code></td>
<td>문자 클래스</td>
<td><code>[abc]</code> → &#39;a&#39;, &#39;b&#39;, &#39;c&#39; 중 하나와 매칭</td>
</tr>
<tr>
<td><code>\d</code></td>
<td>숫자</td>
<td><code>\d+</code> → 숫자 하나 이상 찾기</td>
</tr>
<tr>
<td><code>\D</code></td>
<td>숫자가 아닌 문자</td>
<td><code>\D+</code> → 숫자가 아닌 문자 찾기</td>
</tr>
<tr>
<td><code>\w</code></td>
<td>알파벳, 숫자, <code>_</code></td>
<td><code>\w+</code> → 단어 찾기</td>
</tr>
<tr>
<td><code>\W</code></td>
<td>특수문자</td>
<td><code>\W+</code> → 특수문자 찾기</td>
</tr>
<tr>
<td><code>\s</code></td>
<td>공백 문자</td>
<td><code>\s+</code> → 공백 찾기</td>
</tr>
<tr>
<td><code>\S</code></td>
<td>공백이 아닌 문자</td>
<td><code>\S+</code> → 공백이 아닌 문자 찾기</td>
</tr>
<tr>
<td><code>.</code></td>
<td>모든 문자</td>
<td><code>a.b</code> → a와 b 사이에 한 글자 있는 경우</td>
</tr>
</tbody></table>
<p>2-3. 메타 문자 예제</p>
<pre><code class="language-python">import re

text = &quot;apple banana orange&quot;
pattern = r&quot;b.n&quot;

match = re.findall(pattern, text)
print(match)  # [&#39;ban&#39;]
</code></pre>
<ul>
<li><code>b.n</code> → <code>b</code>와 <code>n</code> 사이에 아무 문자나 하나 있는 단어 찾기</li>
</ul>
<hr>
<h1 id="3-수량자quantifiers">3. 수량자(Quantifiers)</h1>
<p>3-1. 수량자의 개념</p>
<ul>
<li>특정 패턴이 <strong>반복되는 횟수</strong>를 지정하는 기호.</li>
<li>패턴이 몇 번 나타나는지 정의할 수 있음.</li>
</ul>
<p>3-2. 주요 수량자</p>
<table>
<thead>
<tr>
<th>수량자</th>
<th>의미</th>
<th>예시</th>
</tr>
</thead>
<tbody><tr>
<td><code>*</code></td>
<td>0개 이상</td>
<td><code>elice*</code> → &quot;elic&quot;, &quot;elice&quot;, &quot;elicee&quot; 가능</td>
</tr>
<tr>
<td><code>+</code></td>
<td>1개 이상</td>
<td><code>elice+</code> → &quot;elice&quot;, &quot;elicee&quot; 가능 (하지만 &quot;elic&quot;는 안 됨)</td>
</tr>
<tr>
<td><code>?</code></td>
<td>0개 또는 1개</td>
<td><code>elice?</code> → &quot;elic&quot;, &quot;elice&quot; 가능</td>
</tr>
<tr>
<td><code>{n}</code></td>
<td>정확히 n개</td>
<td><code>\d{3}</code> → 숫자 3개 연속</td>
</tr>
<tr>
<td><code>{n, m}</code></td>
<td>n개 이상 m개 이하</td>
<td><code>\w{3,5}</code> → 3~5글자 단어 찾기</td>
</tr>
<tr>
<td><code>{n,}</code></td>
<td>n개 이상</td>
<td><code>a{4,}</code> → a가 4개 이상</td>
</tr>
</tbody></table>
<p>3-3. 수량자 예제</p>
<pre><code class="language-python">import re

text = &quot;helloooo world!&quot;
pattern = r&quot;o{2,}&quot;

match = re.findall(pattern, text)
print(match)  # [&#39;oooo&#39;]
</code></pre>
<ul>
<li><code>o{2,}</code> → &quot;o&quot;가 2개 이상 연속된 부분 찾기</li>
</ul>
<hr>
<h1 id="4-그룹grouping-활용">4. 그룹(Grouping) 활용</h1>
<p>4-1. 그룹의 개념</p>
<ul>
<li><code>()</code>를 사용해 <strong>하나의 패턴을 그룹으로 묶을 수 있음</strong>.</li>
<li><code>|</code>(OR)와 함께 사용 가능.</li>
<li>그룹핑을 하면 <strong>재사용</strong>이 가능함.</li>
</ul>
<p>4-2. 그룹을 활용한 패턴 예제</p>
<pre><code class="language-python">import re

text = &quot;elice alice tomato potato&quot;
pattern = r&quot;(e|a)lice&quot;

match = re.findall(pattern, text)
print(match)  # [&#39;e&#39;, &#39;a&#39;]
</code></pre>
<ul>
<li><code>(e|a)lice</code> → <code>elice</code>, <code>alice</code> 둘 다 찾을 수 있음.</li>
</ul>
<p>4-3. 그룹 재사용 예제</p>
<pre><code class="language-python">import re

text = &quot;tomato potato&quot;
pattern = r&quot;(to)ma\\1&quot;

match = re.findall(pattern, text)
print(match)  # [&#39;to&#39;]
</code></pre>
<ul>
<li><code>(to)</code>를 그룹으로 저장하고, 뒤에서 <code>\\1</code>로 재사용 가능.</li>
</ul>
<hr>
]]></description>
        </item>
        <item>
            <title><![CDATA[모듈, 패키지]]></title>
            <link>https://velog.io/@data_lover/%EB%AA%A8%EB%93%88-%ED%8C%A8%ED%82%A4%EC%A7%80</link>
            <guid>https://velog.io/@data_lover/%EB%AA%A8%EB%93%88-%ED%8C%A8%ED%82%A4%EC%A7%80</guid>
            <pubDate>Wed, 12 Mar 2025 07:49:00 GMT</pubDate>
            <description><![CDATA[<h2 id="1-모듈">1. 모듈</h2>
<ul>
<li><strong>모듈(Module)</strong>: 관련된 변수, 함수, 클래스를 포함하는 파이썬 파일 (<code>.py</code> 확장자)</li>
<li><strong>모듈을 사용하는 이유</strong>: 코드 재사용, 유지보수 용이, 기능 분리</li>
<li><strong>기본 공식</strong></li>
</ul>
<pre><code class="language-python">import 모듈이름  # 전체 모듈 가져오기
from 모듈이름 import 함수/변수/클래스  # 특정 기능만 가져오기
</code></pre>
<h3 id="1-1-import-사용하기">1-1. <code>import</code> 사용하기</h3>
<ul>
<li><code>import</code>를 사용하면 모듈 전체를 가져올 수 있음.</li>
<li>모듈명을 앞에 붙여야 함 (<code>모듈명.함수명</code> 형식)</li>
</ul>
<pre><code class="language-python">import math  # math 모듈 가져오기
print(math.sqrt(16))  # 4.0 (제곱근 계산)
</code></pre>
<h3 id="1-2-from--import-사용하기">1-2. <code>from ~ import</code> 사용하기</h3>
<ul>
<li>특정 함수나 변수만 가져와서 사용할 수 있음.</li>
<li>모듈명을 붙이지 않아도 됨.</li>
</ul>
<pre><code class="language-python">from math import sqrt
print(sqrt(25))  # 5.0 (math.sqrt 대신 sqrt 사용 가능)
</code></pre>
<h3 id="1-3-as-별칭-사용하기">1-3. <code>as</code> 별칭 사용하기</h3>
<ul>
<li>모듈명이 길거나 자주 사용할 경우 별칭을 지정할 수 있음.</li>
</ul>
<pre><code class="language-python">import numpy as np  # numpy 모듈을 np로 사용
array = np.array([1, 2, 3])
print(array)  # [1 2 3]
</code></pre>
<hr>
<h2 id="2-random-모듈">2. <code>random</code> 모듈</h2>
<ul>
<li>난수(랜덤한 숫자) 생성을 위한 모듈</li>
<li>프로그램에서 무작위 값을 사용할 때 유용함.</li>
</ul>
<h3 id="2-1-randomrandinta-b---지정-범위의-정수-반환">2-1. <code>random.randint(a, b)</code> - 지정 범위의 정수 반환</h3>
<pre><code class="language-python">import random
num = random.randint(1, 10)  # 1~10 사이 정수 반환
print(num)  # 예: 7
</code></pre>
<h3 id="2-2-randomchoice리스트---리스트에서-랜덤-선택">2-2. <code>random.choice(리스트)</code> - 리스트에서 랜덤 선택</h3>
<ul>
<li>리스트에서 무작위 요소를 선택할 때 사용</li>
</ul>
<pre><code class="language-python">options = [&#39;가위&#39;, &#39;바위&#39;, &#39;보&#39;]
choice = random.choice(options)
print(choice)  # 무작위로 &#39;가위&#39;, &#39;바위&#39;, &#39;보&#39; 중 하나 출력
</code></pre>
<h3 id="2-3-randomshuffle리스트---리스트-요소-섞기">2-3. <code>random.shuffle(리스트)</code> - 리스트 요소 섞기</h3>
<ul>
<li>리스트 내부 요소들의 순서를 랜덤하게 변경</li>
</ul>
<pre><code class="language-python">cards = [1, 2, 3, 4, 5]
random.shuffle(cards)
print(cards)  # 리스트 순서 랜덤하게 변경됨
</code></pre>
<hr>
<h2 id="3-패키지">3. 패키지</h2>
<ul>
<li><strong>패키지(Package)</strong>: 여러 모듈을 포함하는 디렉토리 (폴더)</li>
<li>패키지는 모듈을 체계적으로 관리하는 역할을 함.</li>
<li><strong>패키지 구조 예시</strong></li>
</ul>
<pre><code>my_package/    # 패키지 폴더
  ├── __init__.py  # 패키지를 인식하도록 하는 파일
  ├── module1.py   # 모듈 1
  ├── module2.py   # 모듈 2
</code></pre><ul>
<li><code>__init__.py</code> 파일이 있어야 해당 폴더가 패키지로 인식됨.</li>
</ul>
<h3 id="3-1-패키지-사용하기">3-1. 패키지 사용하기</h3>
<pre><code class="language-python">from my_package import module1
module1.hello()  # module1.py의 hello 함수 실행
</code></pre>
<hr>
<h2 id="4-그외-모듈">4. 그외 모듈</h2>
<table>
<thead>
<tr>
<th>모듈명</th>
<th>설명</th>
</tr>
</thead>
<tbody><tr>
<td><code>os</code></td>
<td>운영체제 기능 (파일, 디렉토리 관리)</td>
</tr>
<tr>
<td><code>sys</code></td>
<td>시스템 정보 및 인자 제어</td>
</tr>
<tr>
<td><code>datetime</code></td>
<td>날짜 및 시간 처리</td>
</tr>
<tr>
<td><code>time</code></td>
<td>시간 지연, 시간 측정</td>
</tr>
<tr>
<td><code>collections</code></td>
<td>고급 자료구조 (deque, Counter 등)</td>
</tr>
<tr>
<td><code>re</code></td>
<td>정규 표현식 처리</td>
</tr>
</tbody></table>
<h3 id="4-1-os-모듈-예제">4-1. <code>os</code> 모듈 예제</h3>
<ul>
<li>현재 작업 디렉토리를 확인하는 방법</li>
</ul>
<pre><code class="language-python">import os
print(os.getcwd())  # 현재 작업 디렉토리 출력
</code></pre>
<h3 id="4-2-datetime-모듈-예제">4-2. <code>datetime</code> 모듈 예제</h3>
<ul>
<li>현재 날짜 및 시간을 가져오기</li>
</ul>
<pre><code class="language-python">import datetime
now = datetime.datetime.now()
print(now)  # 현재 날짜와 시간 출력
</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[메소드 오버라이딩, pass, 예외 처리]]></title>
            <link>https://velog.io/@data_lover/%EB%A9%94%EC%86%8C%EB%93%9C-%EC%98%A4%EB%B2%84%EB%9D%BC%EC%9D%B4%EB%94%A9-pass-%EC%98%88%EC%99%B8-%EC%B2%98%EB%A6%AC</link>
            <guid>https://velog.io/@data_lover/%EB%A9%94%EC%86%8C%EB%93%9C-%EC%98%A4%EB%B2%84%EB%9D%BC%EC%9D%B4%EB%94%A9-pass-%EC%98%88%EC%99%B8-%EC%B2%98%EB%A6%AC</guid>
            <pubDate>Wed, 12 Mar 2025 07:48:05 GMT</pubDate>
            <description><![CDATA[<h2 id="1-메소드-오버라이딩-method-overriding">1. 메소드 오버라이딩 (Method Overriding)</h2>
<ul>
<li>부모 클래스의 메소드를 자식 클래스에서 <strong>다시 정의(재정의)</strong> 하는 것.</li>
<li>같은 이름의 메소드를 새롭게 구현하여 동작을 변경할 수 있음.</li>
<li>상속을 사용할 때, 부모 클래스의 기본 기능을 유지하면서 일부 동작을 변경하고 싶을 때 사용됨.</li>
</ul>
<h3 id="1-1-기본-공식">1-1. 기본 공식</h3>
<pre><code class="language-python">class 부모클래스:
    def 메소드(self):
        동작

class 자식클래스(부모클래스):
    def 메소드(self):  # 부모 메소드를 재정의 (오버라이딩)
        새로운 동작
</code></pre>
<h3 id="1-2-예제">1-2. 예제</h3>
<pre><code class="language-python">class Animal:
    def sound(self):
        print(&quot;동물이 소리를 냅니다.&quot;)

class Dog(Animal):
    def sound(self):  # 부모 클래스의 sound 메소드를 재정의
        print(&quot;멍멍!&quot;)

animal = Animal()
animal.sound()  # 동물이 소리를 냅니다.

dog = Dog()
dog.sound()  # 멍멍!
</code></pre>
<ul>
<li><code>Dog</code> 클래스에서 <code>sound</code> 메소드를 재정의하여, 원래의 동물 소리 대신 강아지 소리가 출력됨.</li>
</ul>
<hr>
<h2 id="2-pass-키워드">2. <code>pass</code> 키워드</h2>
<ul>
<li><strong>코드를 비워둘 때 사용</strong> (아직 구현하지 않은 부분을 임시로 작성할 때 유용).</li>
<li>문법적으로 코드가 있어야 하지만, 실행할 내용이 없을 때 사용됨.</li>
</ul>
<h3 id="2-1-기본-공식">2-1. 기본 공식</h3>
<pre><code class="language-python">class 클래스이름:
    pass  # 클래스가 비어 있어도 오류 발생하지 않음
</code></pre>
<h3 id="2-2-예제">2-2. 예제</h3>
<pre><code class="language-python">class Bird:
    def fly(self):
        pass  # 아직 구현하지 않은 메소드
</code></pre>
<ul>
<li><code>pass</code>를 사용하면 나중에 구현할 코드의 자리를 미리 만들어둘 수 있음.</li>
</ul>
<hr>
<h2 id="3-예외-처리-try-except">3. 예외 처리 (<code>try-except</code>)</h2>
<ul>
<li>프로그램 실행 중 <strong>오류(예외)가 발생해도 멈추지 않고 처리</strong>할 수 있도록 하는 방법.</li>
<li>예외가 발생하면 <code>except</code> 블록이 실행되어 프로그램이 멈추지 않고 계속 실행될 수 있음.</li>
</ul>
<h3 id="3-1-기본-공식">3-1. 기본 공식</h3>
<pre><code class="language-python">try:
    실행할 코드
except 예외종류:
    예외 발생 시 실행할 코드
</code></pre>
<h3 id="3-2-예제">3-2. 예제</h3>
<pre><code class="language-python">try:
    x = 10 / 0  # 0으로 나누기 (오류 발생)
except ZeroDivisionError:
    print(&quot;0으로 나눌 수 없습니다!&quot;)
</code></pre>
<p>출력:</p>
<pre><code>0으로 나눌 수 없습니다!
</code></pre><ul>
<li><code>10 / 0</code> 연산은 <code>ZeroDivisionError</code> 예외를 발생시키므로 <code>except</code> 블록이 실행됨.</li>
</ul>
<hr>
<h2 id="4-try-except-else-finally">4. <code>try-except-else-finally</code></h2>
<ul>
<li><strong><code>else</code></strong>: 예외가 발생하지 않을 때 실행.</li>
<li><strong><code>finally</code></strong>: 예외 발생 여부와 관계없이 <strong>무조건 실행</strong>.</li>
</ul>
<h3 id="4-1-기본-공식">4-1. 기본 공식</h3>
<pre><code class="language-python">try:
    실행할 코드
except 예외종류:
    예외 발생 시 실행할 코드
else:
    예외가 발생하지 않았을 때 실행할 코드
finally:
    항상 실행할 코드
</code></pre>
<h3 id="4-2-예제">4-2. 예제</h3>
<pre><code class="language-python">try:
    num = int(input(&quot;숫자를 입력하세요: &quot;))
    result = 10 / num
except ValueError:
    print(&quot;숫자가 아닙니다!&quot;)
except ZeroDivisionError:
    print(&quot;0으로 나눌 수 없습니다!&quot;)
else:
    print(&quot;결과:&quot;, result)
finally:
    print(&quot;프로그램 종료&quot;)
</code></pre>
<p><strong>입력값 예시 1:</strong> <code>2</code></p>
<pre><code>결과: 5.0
프로그램 종료
</code></pre><p><strong>입력값 예시 2:</strong> <code>0</code></p>
<pre><code>0으로 나눌 수 없습니다!
프로그램 종료
</code></pre><p><strong>입력값 예시 3:</strong> <code>a</code></p>
<pre><code>숫자가 아닙니다!
프로그램 종료
</code></pre><ul>
<li><code>else</code>는 예외가 발생하지 않은 경우 실행됨.</li>
<li><code>finally</code>는 어떤 경우에도 실행됨.</li>
</ul>
<hr>
<h2 id="5-에러-종류">5. 에러 종류</h2>
<table>
<thead>
<tr>
<th>에러 종류</th>
<th>설명</th>
</tr>
</thead>
<tbody><tr>
<td><code>ZeroDivisionError</code></td>
<td>0으로 나누기 오류</td>
</tr>
<tr>
<td><code>ValueError</code></td>
<td>형 변환 오류 (예: <code>int(&quot;a&quot;)</code>)</td>
</tr>
<tr>
<td><code>IndexError</code></td>
<td>리스트 인덱스 범위 초과 오류</td>
</tr>
<tr>
<td><code>KeyError</code></td>
<td>딕셔너리에서 존재하지 않는 키 접근</td>
</tr>
<tr>
<td><code>TypeError</code></td>
<td>연산이 불가능한 타입 사용</td>
</tr>
<tr>
<td><code>FileNotFoundError</code></td>
<td>존재하지 않는 파일 열기</td>
</tr>
</tbody></table>
<h3 id="5-1-예제">5-1. 예제</h3>
<pre><code class="language-python">try:
    my_list = [1, 2, 3]
    print(my_list[5])  # 리스트 범위 초과 (IndexError 발생)
except IndexError:
    print(&quot;인덱스 범위를 벗어났습니다!&quot;)
</code></pre>
<p>출력:</p>
<pre><code>인덱스 범위를 벗어났습니다!
</code></pre><ul>
<li><code>my_list[5]</code>는 존재하지 않는 인덱스를 참조하기 때문에 <code>IndexError</code>가 발생하여 <code>except</code> 블록이 실행됨.</li>
</ul>
<hr>
]]></description>
        </item>
        <item>
            <title><![CDATA[클래스, 객체]]></title>
            <link>https://velog.io/@data_lover/%ED%81%B4%EB%9E%98%EC%8A%A4-%EA%B0%9D%EC%B2%B4</link>
            <guid>https://velog.io/@data_lover/%ED%81%B4%EB%9E%98%EC%8A%A4-%EA%B0%9D%EC%B2%B4</guid>
            <pubDate>Wed, 12 Mar 2025 07:46:52 GMT</pubDate>
            <description><![CDATA[<h2 id="1-클래스">1. 클래스</h2>
<ul>
<li>클래스(Class)는 객체(Object)를 생성하기 위한 <strong>설계도</strong> 또는 <strong>틀</strong>.</li>
<li>클래스 안에는 <strong>변수(속성)</strong>와 <strong>함수(메소드)</strong>가 포함됨.</li>
<li>객체는 클래스를 기반으로 만들어지는 <strong>실제 데이터가 담긴 실체</strong>.</li>
</ul>
<h3 id="1-1-기본-공식">1-1. 기본 공식</h3>
<pre><code class="language-python">class 클래스이름:
    def __init__(self):
        # 생성자 (객체가 생성될 때 자동 실행)
        pass
</code></pre>
<h3 id="1-2-예제">1-2. 예제</h3>
<pre><code class="language-python">class Person:
    def __init__(self, name, age):
        self.name = name  # 멤버 변수
        self.age = age

person1 = Person(&quot;공주&quot;, 20)  # 객체 생성
print(person1.name, person1.age)  # 공주 20
</code></pre>
<hr>
<h2 id="2-__init__-생성자">2. <code>__init__</code> (생성자)</h2>
<ul>
<li>객체가 생성될 때 자동으로 실행되는 메소드.</li>
<li>주로 <strong>초기값을 설정하는 역할</strong>.</li>
</ul>
<h3 id="2-1-기본-공식">2-1. 기본 공식</h3>
<pre><code class="language-python">class 클래스이름:
    def __init__(self, 매개변수):
        self.변수 = 매개변수
</code></pre>
<h3 id="2-2-예제">2-2. 예제</h3>
<pre><code class="language-python">class Animal:
    def __init__(self, species):
        self.species = species  # 멤버 변수 설정

animal = Animal(&quot;고양이&quot;)
print(animal.species)  # 고양이
</code></pre>
<hr>
<h2 id="3-멤버-변수">3. 멤버 변수</h2>
<ul>
<li>클래스 내부에서 선언된 변수로, 객체의 <strong>속성</strong>을 저장.</li>
<li><code>self.변수명</code> 형식으로 사용.</li>
</ul>
<h3 id="3-1-기본-공식">3-1. 기본 공식</h3>
<pre><code class="language-python">class 클래스이름:
    def __init__(self, 값):
        self.변수명 = 값
</code></pre>
<h3 id="3-2-예제">3-2. 예제</h3>
<pre><code class="language-python">class Car:
    def __init__(self, brand):
        self.brand = brand

car1 = Car(&quot;Hyundai&quot;)
print(car1.brand)  # Hyundai
</code></pre>
<hr>
<h2 id="4-메소드">4. 메소드</h2>
<ul>
<li>클래스 내부에서 정의된 함수로, 객체의 동작을 정의함.</li>
</ul>
<h3 id="4-1-기본-공식">4-1. 기본 공식</h3>
<pre><code class="language-python">class 클래스이름:
    def 메소드이름(self):
        동작
</code></pre>
<h3 id="4-2-예제">4-2. 예제</h3>
<pre><code class="language-python">class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print(self.name, &quot;가 멍멍!&quot;)

dog1 = Dog(&quot;초코&quot;)
dog1.bark()  # 초코 가 멍멍!
</code></pre>
<hr>
<h2 id="5-self">5. <code>self</code></h2>
<ul>
<li>클래스 내부에서 객체 자기 자신을 가리키는 키워드.</li>
<li>멤버 변수와 메소드를 호출할 때 반드시 사용.</li>
</ul>
<h3 id="5-1-기본-공식">5-1. 기본 공식</h3>
<pre><code class="language-python">class 클래스이름:
    def 메소드(self):
        print(self.변수명)
</code></pre>
<h3 id="5-2-예제">5-2. 예제</h3>
<pre><code class="language-python">class Cat:
    def __init__(self, name):
        self.name = name

    def meow(self):
        print(self.name, &quot;야옹!&quot;)

cat1 = Cat(&quot;나비&quot;)
cat1.meow()  # 나비 야옹!
</code></pre>
<hr>
<h2 id="6-상속-inheritance">6. 상속 (<code>Inheritance</code>)</h2>
<ul>
<li>기존 클래스를 확장하여 새로운 클래스를 만드는 개념.</li>
<li>코드 재사용성이 높아짐.</li>
</ul>
<h3 id="6-1-기본-공식">6-1. 기본 공식</h3>
<pre><code class="language-python">class 부모클래스:
    pass

class 자식클래스(부모클래스):
    pass
</code></pre>
<h3 id="6-2-예제">6-2. 예제</h3>
<pre><code class="language-python">class Animal:
    def sound(self):
        print(&quot;동물이 소리를 냅니다.&quot;)

class Dog(Animal):
    def bark(self):
        print(&quot;멍멍!&quot;)

dog = Dog()
dog.sound()  # 동물이 소리를 냅니다.
dog.bark()   # 멍멍!
</code></pre>
<hr>
<h2 id="7-super">7. <code>super()</code></h2>
<ul>
<li>부모 클래스의 기능을 자식 클래스에서 호출할 때 사용.</li>
</ul>
<h3 id="7-1-기본-공식">7-1. 기본 공식</h3>
<pre><code class="language-python">class 부모클래스:
    def __init__(self, 값):
        self.변수 = 값

class 자식클래스(부모클래스):
    def __init__(self, 값):
        super().__init__(값)
</code></pre>
<h3 id="7-2-예제">7-2. 예제</h3>
<pre><code class="language-python">class Parent:
    def __init__(self, name):
        self.name = name

class Child(Parent):
    def __init__(self, name, age):
        super().__init__(name)
        self.age = age

child = Child(&quot;공주&quot;, 10)
print(child.name, child.age)  # 공주 10
</code></pre>
<hr>
<h2 id="8-다중-상속">8. 다중 상속</h2>
<ul>
<li>두 개 이상의 부모 클래스를 상속받는 것.</li>
</ul>
<h3 id="8-1-기본-공식">8-1. 기본 공식</h3>
<pre><code class="language-python">class 부모클래스1:
    pass

class 부모클래스2:
    pass

class 자식클래스(부모클래스1, 부모클래스2):
    pass
</code></pre>
<h3 id="8-2-예제">8-2. 예제</h3>
<pre><code class="language-python">class Flyer:
    def fly(self):
        print(&quot;날 수 있습니다!&quot;)

class Swimmer:
    def swim(self):
        print(&quot;수영할 수 있습니다!&quot;)

class Duck(Flyer, Swimmer):
    pass

duck = Duck()
duck.fly()  # 날 수 있습니다!
duck.swim()  # 수영할 수 있습니다!
</code></pre>
<hr>
]]></description>
        </item>
        <item>
            <title><![CDATA[사용자 입력, 파일 입출력]]></title>
            <link>https://velog.io/@data_lover/%EC%82%AC%EC%9A%A9%EC%9E%90-%EC%9E%85%EB%A0%A5-%ED%8C%8C%EC%9D%BC-%EC%9E%85%EC%B6%9C%EB%A0%A5</link>
            <guid>https://velog.io/@data_lover/%EC%82%AC%EC%9A%A9%EC%9E%90-%EC%9E%85%EB%A0%A5-%ED%8C%8C%EC%9D%BC-%EC%9E%85%EC%B6%9C%EB%A0%A5</guid>
            <pubDate>Wed, 12 Mar 2025 07:45:28 GMT</pubDate>
            <description><![CDATA[<h2 id="1-사용자-입력-input">1. 사용자 입력 (<code>input()</code>)</h2>
<h3 id="1-1-기본-개념">1-1. 기본 개념</h3>
<ul>
<li>사용자가 키보드로 입력한 값을 프로그램에서 받을 때 사용.</li>
<li>항상 문자열(<code>str</code>) 타입으로 반환됨.</li>
</ul>
<h3 id="기본-공식">기본 공식</h3>
<pre><code class="language-python">변수 = input(&quot;입력 안내 문구&quot;)
</code></pre>
<h3 id="예제">예제</h3>
<pre><code class="language-python">name = input(&quot;이름을 입력하세요: &quot;)
print(&quot;안녕하세요,&quot;, name, &quot;님!&quot;)  # 예: 이름이 &#39;공주&#39;라면 &#39;안녕하세요, 공주 님!&#39; 출력
</code></pre>
<h3 id="1-2-숫자-입력-받기">1-2. 숫자 입력 받기</h3>
<ul>
<li><code>input()</code>은 문자열을 반환하므로, 숫자로 사용하려면 형 변환이 필요함.</li>
</ul>
<h3 id="기본-공식-1">기본 공식</h3>
<pre><code class="language-python">변수 = 데이터타입(input(&quot;입력 안내 문구&quot;))
</code></pre>
<h3 id="예제-1">예제</h3>
<pre><code class="language-python">age = int(input(&quot;나이를 입력하세요: &quot;))
print(&quot;내년 나이는&quot;, age + 1, &quot;살입니다.&quot;)  # 입력값이 25라면 &#39;내년 나이는 26살입니다.&#39; 출력
</code></pre>
<hr>
<h2 id="2-파일-입출력-open">2. 파일 입출력 (<code>open()</code>)</h2>
<h3 id="2-1-open-함수-개요">2-1. <code>open()</code> 함수 개요</h3>
<ul>
<li>파일을 열고 조작할 수 있도록 해줌.</li>
</ul>
<h3 id="기본-공식-2">기본 공식</h3>
<pre><code class="language-python">파일객체 = open(파일명, 열기모드, encoding=&quot;인코딩&quot;)
</code></pre>
<h3 id="예제-2">예제</h3>
<pre><code class="language-python">file = open(&quot;example.txt&quot;, &quot;w&quot;, encoding=&quot;utf-8&quot;)
file.write(&quot;파일 테스트입니다.\n&quot;)
file.close()
</code></pre>
<h3 id="2-2-열기-모드">2-2. 열기 모드</h3>
<table>
<thead>
<tr>
<th>모드</th>
<th>설명</th>
</tr>
</thead>
<tbody><tr>
<td><code>r</code></td>
<td>읽기 모드 (파일이 존재해야 함)</td>
</tr>
<tr>
<td><code>w</code></td>
<td>쓰기 모드 (파일이 없으면 생성, 있으면 덮어씀)</td>
</tr>
<tr>
<td><code>a</code></td>
<td>추가 모드 (파일이 없으면 생성, 있으면 내용 추가)</td>
</tr>
</tbody></table>
<hr>
<h2 id="3-파일-쓰기">3. 파일 쓰기</h2>
<h3 id="3-1-기본-파일-쓰기-w-모드">3-1. 기본 파일 쓰기 (<code>w</code> 모드)</h3>
<h3 id="기본-공식-3">기본 공식</h3>
<pre><code class="language-python">파일객체 = open(파일명, &quot;w&quot;, encoding=&quot;인코딩&quot;)
파일객체.write(내용)
파일객체.close()
</code></pre>
<h3 id="예제-3">예제</h3>
<pre><code class="language-python">file = open(&quot;example.txt&quot;, &quot;w&quot;, encoding=&quot;utf-8&quot;)
file.write(&quot;첫 번째 줄\n&quot;)
file.write(&quot;두 번째 줄\n&quot;)
file.close()
</code></pre>
<h3 id="3-2-추가-모드-a-모드">3-2. 추가 모드 (<code>a</code> 모드)</h3>
<h3 id="기본-공식-4">기본 공식</h3>
<pre><code class="language-python">파일객체 = open(파일명, &quot;a&quot;, encoding=&quot;인코딩&quot;)
파일객체.write(추가할_내용)
파일객체.close()
</code></pre>
<h3 id="예제-4">예제</h3>
<pre><code class="language-python">file = open(&quot;example.txt&quot;, &quot;a&quot;, encoding=&quot;utf-8&quot;)
file.write(&quot;세 번째 줄 추가\n&quot;)
file.close()
</code></pre>
<hr>
<h2 id="4-파일-읽기">4. 파일 읽기</h2>
<h3 id="4-1-전체-읽기-read">4-1. 전체 읽기 (<code>read()</code>)</h3>
<h3 id="기본-공식-5">기본 공식</h3>
<pre><code class="language-python">파일객체 = open(파일명, &quot;r&quot;, encoding=&quot;인코딩&quot;)
내용 = 파일객체.read()
파일객체.close()
</code></pre>
<h3 id="예제-5">예제</h3>
<pre><code class="language-python">file = open(&quot;example.txt&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;)
content = file.read()
print(content)
file.close()
</code></pre>
<h3 id="4-2-한-줄씩-읽기-readline">4-2. 한 줄씩 읽기 (<code>readline()</code>)</h3>
<h3 id="기본-공식-6">기본 공식</h3>
<pre><code class="language-python">파일객체 = open(파일명, &quot;r&quot;, encoding=&quot;인코딩&quot;)
한줄 = 파일객체.readline()
파일객체.close()
</code></pre>
<h3 id="예제-6">예제</h3>
<pre><code class="language-python">file = open(&quot;example.txt&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;)
line = file.readline()
print(line, end=&quot;&quot;)
line = file.readline()
print(line, end=&quot;&quot;)
file.close()
</code></pre>
<h3 id="4-3-모든-줄을-리스트로-읽기-readlines">4-3. 모든 줄을 리스트로 읽기 (<code>readlines()</code>)</h3>
<h3 id="기본-공식-7">기본 공식</h3>
<pre><code class="language-python">파일객체 = open(파일명, &quot;r&quot;, encoding=&quot;인코딩&quot;)
리스트 = 파일객체.readlines()
파일객체.close()
</code></pre>
<h3 id="예제-7">예제</h3>
<pre><code class="language-python">file = open(&quot;example.txt&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;)
lines = file.readlines()
for line in lines:
    print(line, end=&quot;&quot;)
file.close()
</code></pre>
<hr>
<h2 id="5-with문을-사용한-파일-입출력">5. <code>with</code>문을 사용한 파일 입출력</h2>
<ul>
<li>파일을 열고 자동으로 닫아줌 (<code>close()</code> 필요 없음)</li>
</ul>
<h3 id="5-1-파일-쓰기-with-사용">5-1. 파일 쓰기 (<code>with</code> 사용)</h3>
<h3 id="기본-공식-8">기본 공식</h3>
<pre><code class="language-python">with open(파일명, &quot;w&quot;, encoding=&quot;인코딩&quot;) as 파일객체:
    파일객체.write(내용)
</code></pre>
<h3 id="예제-8">예제</h3>
<pre><code class="language-python">with open(&quot;example.txt&quot;, &quot;w&quot;, encoding=&quot;utf-8&quot;) as file:
    file.write(&quot;with 문을 사용한 파일 쓰기\n&quot;)
</code></pre>
<h3 id="5-2-파일-읽기-with-사용">5-2. 파일 읽기 (<code>with</code> 사용)</h3>
<h3 id="기본-공식-9">기본 공식</h3>
<pre><code class="language-python">with open(파일명, &quot;r&quot;, encoding=&quot;인코딩&quot;) as 파일객체:
    내용 = 파일객체.read()
</code></pre>
<h3 id="예제-9">예제</h3>
<pre><code class="language-python">with open(&quot;example.txt&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;) as file:
    content = file.read()
    print(content)
</code></pre>
<hr>
]]></description>
        </item>
        <item>
            <title><![CDATA[리스트 컴프리헨션, 함수]]></title>
            <link>https://velog.io/@data_lover/%EB%A6%AC%EC%8A%A4%ED%8A%B8-%EC%BB%B4%ED%94%84%EB%A6%AC%ED%97%A8%EC%85%98-%ED%95%A8%EC%88%98</link>
            <guid>https://velog.io/@data_lover/%EB%A6%AC%EC%8A%A4%ED%8A%B8-%EC%BB%B4%ED%94%84%EB%A6%AC%ED%97%A8%EC%85%98-%ED%95%A8%EC%88%98</guid>
            <pubDate>Wed, 12 Mar 2025 07:44:29 GMT</pubDate>
            <description><![CDATA[<h2 id="1-리스트-컴프리헨션">1. 리스트 컴프리헨션</h2>
<h3 id="1-1-기본-개념">1-1. 기본 개념</h3>
<ul>
<li>리스트를 빠르고 간결하게 생성하는 방법.</li>
<li>일반적인 <code>for</code> 문을 한 줄로 작성 가능.</li>
<li>기본 구조:</li>
</ul>
<pre><code class="language-python">[표현식 for 변수 in 반복가능한객체 if 조건]
</code></pre>
<h3 id="1-2-기본-예제">1-2. 기본 예제</h3>
<pre><code class="language-python">numbers = [x for x in range(5)]
print(numbers)  # 출력: [0, 1, 2, 3, 4]
</code></pre>
<h3 id="1-3-조건문-추가">1-3. 조건문 추가</h3>
<pre><code class="language-python">even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)  # 출력: [0, 2, 4, 6, 8]
</code></pre>
<h3 id="1-4-중첩-반복문-사용">1-4. 중첩 반복문 사용</h3>
<pre><code class="language-python">pairs = [(x, y) for x in range(2) for y in range(3)]
print(pairs)  # 출력: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
</code></pre>
<h2 id="2-함수">2. 함수</h2>
<h3 id="2-1-함수-정의">2-1. 함수 정의</h3>
<ul>
<li>특정 작업을 수행하는 코드 블록.</li>
<li><code>def</code> 키워드를 사용하여 정의.</li>
</ul>
<pre><code class="language-python">def hello():
    print(&quot;안녕하세요!&quot;)
hello()  # 출력: 안녕하세요!
</code></pre>
<h3 id="2-2-전달값-매개변수">2-2. 전달값 (매개변수)</h3>
<ul>
<li>함수를 호출할 때 값을 전달하여 동작을 조절할 수 있음.</li>
</ul>
<pre><code class="language-python">def greet(name):
    print(f&quot;안녕하세요, {name}님!&quot;)
greet(&quot;철수&quot;)  # 출력: 안녕하세요, 철수님!
</code></pre>
<h3 id="2-3-반환값">2-3. 반환값</h3>
<ul>
<li>함수에서 값을 돌려줄 때 <code>return</code> 사용.</li>
</ul>
<pre><code class="language-python">def add(a, b):
    return a + b
result = add(3, 5)
print(result)  # 출력: 8
</code></pre>
<h3 id="2-4-기본값-설정">2-4. 기본값 설정</h3>
<ul>
<li>매개변수에 기본값을 지정 가능.</li>
</ul>
<pre><code class="language-python">def introduce(name, age=20):
    print(f&quot;이름: {name}, 나이: {age}&quot;)
introduce(&quot;영희&quot;)  # 출력: 이름: 영희, 나이: 20
introduce(&quot;민수&quot;, 25)  # 출력: 이름: 민수, 나이: 25
</code></pre>
<h3 id="2-5-키워드-인자">2-5. 키워드 인자</h3>
<ul>
<li>매개변수 이름을 명시적으로 지정하여 전달.</li>
</ul>
<pre><code class="language-python">def describe_pet(animal, name):
    print(f&quot;종: {animal}, 이름: {name}&quot;)
describe_pet(name=&quot;코코&quot;, animal=&quot;강아지&quot;)  # 출력: 종: 강아지, 이름: 코코
</code></pre>
<h3 id="2-6-가변-인자-args">2-6. 가변 인자 (*args)</h3>
<ul>
<li>여러 개의 값을 전달할 수 있음.</li>
</ul>
<pre><code class="language-python">def sum_numbers(*numbers):
    return sum(numbers)
print(sum_numbers(1, 2, 3, 4, 5))  # 출력: 15
</code></pre>
<h3 id="2-7-지역변수와-전역변수">2-7. 지역변수와 전역변수</h3>
<ul>
<li><strong>지역변수</strong>: 함수 내부에서만 사용되는 변수.</li>
<li><strong>전역변수</strong>: 함수 바깥에서 선언된 변수로 함수 내부에서도 접근 가능.</li>
</ul>
<pre><code class="language-python">global_var = &quot;전역변수&quot;

def example():
    local_var = &quot;지역변수&quot;
    print(global_var)  # 출력: 전역변수
    print(local_var)  # 출력: 지역변수

example()
print(global_var)  # 출력: 전역변수
# print(local_var)  # 오류 발생 (지역변수는 함수 밖에서 사용 불가)
</code></pre>
<pre><code class="language-python">message = &quot;전역 변수입니다.&quot;  # 전역 변수

def example():
    message = &quot;지역 변수입니다.&quot;  # 지역 변수 (함수 내부에서 새롭게 정의)
    print(&quot;함수 내부:&quot;, message)  # 출력: 함수 내부: 지역 변수입니다.

example()
print(&quot;함수 외부:&quot;, message)  # 출력: 함수 외부: 전역 변수입니다.
</code></pre>
<ul>
<li><p>설명</p>
<ul>
<li><code>message</code>라는 변수가 함수 바깥과 안에서 각각 정의됨.</li>
<li>함수 내부에서 <code>message = &quot;지역 변수입니다.&quot;</code>라고 하면, <strong>이 변수는 함수 안에서만 존재하는 지역 변수</strong>가 됨.</li>
<li><code>example()</code>을 호출하면 지역 변수가 사용되고, 함수 호출이 끝난 후에는 여전히 전역 변수 <code>message</code>가 유지됨.</li>
</ul>
</li>
<li><p><strong>global 키워드 사용</strong></p>
<p>함수 내부에서도 전역 변수 값을 변경할 수 있음.</p>
</li>
</ul>
<pre><code class="language-python">count = 0

def increase():
    global count  # 전역 변수 수정
    count += 1
    print(count)

increase()  # 출력: 1
increase()  # 출력: 2
</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[while 반복문, 제어문]]></title>
            <link>https://velog.io/@data_lover/while-%EB%B0%98%EB%B3%B5%EB%AC%B8-%EC%A0%9C%EC%96%B4%EB%AC%B8</link>
            <guid>https://velog.io/@data_lover/while-%EB%B0%98%EB%B3%B5%EB%AC%B8-%EC%A0%9C%EC%96%B4%EB%AC%B8</guid>
            <pubDate>Wed, 12 Mar 2025 07:43:30 GMT</pubDate>
            <description><![CDATA[<h2 id="1-while-반복문">1. while 반복문</h2>
<h3 id="1-1-기본-구조">1-1. 기본 구조</h3>
<pre><code class="language-python">while 조건:
    실행할 코드
</code></pre>
<ul>
<li>조건이 <code>True</code>인 동안 반복 실행됨.</li>
<li>조건이 <code>False</code>가 되면 반복 종료.</li>
</ul>
<h3 id="예제">예제</h3>
<pre><code class="language-python">count = 0
while count &lt; 5:
    print(count)  # 출력: 0, 1, 2, 3, 4
    count += 1
</code></pre>
<h2 id="2-break-문">2. break 문</h2>
<h3 id="2-1-기본-구조">2-1. 기본 구조</h3>
<pre><code class="language-python">while 조건:
    실행할 코드
    if 종료조건:
        break  # 반복문 즉시 종료
</code></pre>
<ul>
<li><code>break</code>를 만나면 반복문을 즉시 빠져나감.</li>
</ul>
<h3 id="예제-1">예제</h3>
<pre><code class="language-python">num = 1
while num &lt;= 10:
    if num == 5:
        break  # num이 5가 되면 종료
    print(num)  # 출력: 1, 2, 3, 4
    num += 1
</code></pre>
<h2 id="3-continue-문">3. continue 문</h2>
<h3 id="3-1-기본-구조">3-1. 기본 구조</h3>
<pre><code class="language-python">while 조건:
    실행할 코드
    if 건너뛸조건:
        continue  # 이후 코드 실행하지 않고 다음 반복 진행
</code></pre>
<ul>
<li><code>continue</code>를 만나면 아래 코드 실행 없이 다음 반복으로 넘어감.</li>
</ul>
<h3 id="예제-2">예제</h3>
<pre><code class="language-python">num = 0
while num &lt; 5:
    num += 1
    if num == 3:
        continue  # num이 3일 때 아래 코드 건너뜀
    print(num)  # 출력: 1, 2, 4, 5
</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[if 조건문, for 반복문]]></title>
            <link>https://velog.io/@data_lover/if-%EC%A1%B0%EA%B1%B4%EB%AC%B8-for-%EB%B0%98%EB%B3%B5%EB%AC%B8-v3hfrzbt</link>
            <guid>https://velog.io/@data_lover/if-%EC%A1%B0%EA%B1%B4%EB%AC%B8-for-%EB%B0%98%EB%B3%B5%EB%AC%B8-v3hfrzbt</guid>
            <pubDate>Wed, 12 Mar 2025 07:42:25 GMT</pubDate>
            <description><![CDATA[<h2 id="1-if-조건문">1. if 조건문</h2>
<p>1-1. 기본 구조</p>
<pre><code class="language-python">if 조건:
    실행할 코드
</code></pre>
<ul>
<li>조건이 <code>True</code>일 경우에만 실행됨.</li>
</ul>
<h3 id="예제">예제</h3>
<pre><code class="language-python">x = 10
if x &gt; 5:
    print(&quot;x는 5보다 큽니다.&quot;)  # 출력: x는 5보다 큽니다.
</code></pre>
<p>1-2. else 추가</p>
<pre><code class="language-python">if 조건:
    실행할 코드
else:
    조건이 거짓일 때 실행할 코드
</code></pre>
<ul>
<li><code>if</code> 조건이 <code>False</code>일 경우 <code>else</code> 블록이 실행됨.</li>
</ul>
<h3 id="예제-1">예제</h3>
<pre><code class="language-python">x = 3
if x &gt; 5:
    print(&quot;x는 5보다 큽니다.&quot;)
else:
    print(&quot;x는 5 이하입니다.&quot;)  # 출력: x는 5 이하입니다.
</code></pre>
<p>1-3. elif 추가 (다중 조건)</p>
<pre><code class="language-python">if 조건1:
    실행할 코드
elif 조건2:
    실행할 코드
else:
    위 조건이 모두 거짓일 때 실행할 코드
</code></pre>
<ul>
<li>여러 개의 조건을 순차적으로 비교하며, 첫 번째로 참인 조건만 실행됨.</li>
</ul>
<h3 id="예제-2">예제</h3>
<pre><code class="language-python">score = 75
if score &gt;= 90:
    print(&quot;A 학점&quot;)
elif score &gt;= 80:
    print(&quot;B 학점&quot;)
elif score &gt;= 70:
    print(&quot;C 학점&quot;)  # 출력: C 학점
else:
    print(&quot;D 학점&quot;)
</code></pre>
<p>1-4. if, elif, else 혼합 예제</p>
<pre><code class="language-python">age = 20
if age &lt; 13:
    print(&quot;어린이&quot;)
elif 13 &lt;= age &lt; 20:
    print(&quot;청소년&quot;)
else:
    print(&quot;성인&quot;)  # 출력: 성인
</code></pre>
<h2 id="2-if-중첩">2. if 중첩</h2>
<pre><code class="language-python">score = 85
if score &gt;= 60:
    print(&quot;합격&quot;)  # 출력: 합격
    if score &gt;= 90:
        print(&quot;우수&quot;)
    else:
        print(&quot;보통&quot;)  # 출력: 보통
else:
    print(&quot;불합격&quot;)
</code></pre>
<ul>
<li><code>if</code> 내부에 또 다른 <code>if</code>를 넣을 수 있음.</li>
</ul>
<h2 id="3-for-반복문">3. for 반복문</h2>
<p>3-1. 기본 구조</p>
<pre><code class="language-python">for 변수 in 반복가능한객체:
    실행할 코드
</code></pre>
<ul>
<li>리스트, 튜플, 문자열 등 반복 가능한 객체를 순차적으로 순회함.</li>
</ul>
<h3 id="예제-3">예제</h3>
<pre><code class="language-python">for i in [1, 2, 3]:
    print(i)  # 출력: 1, 2, 3
</code></pre>
<p>3-2. range() 함수 활용</p>
<pre><code class="language-python">for i in range(5):  # 0부터 4까지 반복
    print(i)  # 출력: 0, 1, 2, 3, 4
</code></pre>
<p>3-3. range()의 다양한 사용법</p>
<pre><code class="language-python">for i in range(2, 10, 2):  # 2부터 9까지 2씩 증가
    print(i)  # 출력: 2, 4, 6, 8
</code></pre>
<ul>
<li><code>range(n)</code>: 0부터 n-1까지</li>
<li><code>range(a, b)</code>: a부터 b-1까지</li>
<li><code>range(a, b, step)</code>: a부터 b-1까지 step 간격으로</li>
</ul>
<h2 id="4-for-반복문-활용">4. for 반복문 활용</h2>
<p>4-1. 리스트</p>
<pre><code class="language-python">fruits = [&quot;사과&quot;, &quot;바나나&quot;, &quot;체리&quot;]
for fruit in fruits:
    print(fruit)  # 출력: 사과, 바나나, 체리
</code></pre>
<p>4-2. 튜플</p>
<pre><code class="language-python">tuple_data = (1, 2, 3)
for num in tuple_data:
    print(num)  # 출력: 1, 2, 3
</code></pre>
<p>4-3. 딕셔너리</p>
<pre><code class="language-python">scores = {&quot;철수&quot;: 90, &quot;영희&quot;: 85, &quot;민수&quot;: 80}
for key, value in scores.items():
    print(f&quot;{key}: {value}&quot;)  # 출력: 철수: 90, 영희: 85, 민수: 80
</code></pre>
<p>4-4. 문자열</p>
<pre><code class="language-python">for char in &quot;Python&quot;:
    print(char)  # 출력: P, y, t, h, o, n
</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[탈출문자, 자료형 정리]]></title>
            <link>https://velog.io/@data_lover/%ED%83%88%EC%B6%9C%EB%AC%B8%EC%9E%90-%EC%9E%90%EB%A3%8C%ED%98%95-%EC%A0%95%EB%A6%AC</link>
            <guid>https://velog.io/@data_lover/%ED%83%88%EC%B6%9C%EB%AC%B8%EC%9E%90-%EC%9E%90%EB%A3%8C%ED%98%95-%EC%A0%95%EB%A6%AC</guid>
            <pubDate>Wed, 12 Mar 2025 07:41:09 GMT</pubDate>
            <description><![CDATA[<h2 id="1-탈출문자">1. 탈출문자</h2>
<ul>
<li>문자열에서 특정 기능을 수행하는 특수 문자</li>
<li><code>\</code> 기호와 함께 사용됨</li>
</ul>
<table>
<thead>
<tr>
<th>탈출문자</th>
<th>설명</th>
<th>예시</th>
</tr>
</thead>
<tbody><tr>
<td><code>\n</code></td>
<td>줄바꿈</td>
<td><code>print(&quot;Hello\nWorld&quot;)</code> → Hello (줄바꿈) World</td>
</tr>
<tr>
<td><code>\t</code></td>
<td>탭(공백 4칸)</td>
<td><code>print(&quot;Hello\tWorld&quot;)</code> → Hello    World</td>
</tr>
<tr>
<td><code>\\</code></td>
<td>백슬래시 출력</td>
<td><code>print(&quot;C:\\Users&quot;)</code> → C:\Users</td>
</tr>
<tr>
<td><code>\&#39;</code></td>
<td>작은따옴표 출력</td>
<td><code>print(&#39;It\&#39;s OK&#39;)</code> → It&#39;s OK</td>
</tr>
<tr>
<td><code>\&quot;</code></td>
<td>큰따옴표 출력</td>
<td><code>print(&quot;He said, \&quot;Hello!\&quot;&quot;)</code> → He said, &quot;Hello!&quot;</td>
</tr>
</tbody></table>
<hr>
<h2 id="2-리스트-list">2. 리스트 (List)</h2>
<ul>
<li>여러 개의 데이터를 순서대로 저장하는 자료형</li>
<li>대괄호 <code>[]</code>를 사용하며, 다양한 자료형을 포함 가능</li>
<li>변경(수정, 추가, 삭제) 가능</li>
</ul>
<h3 id="2-1-리스트-메서드">2-1. 리스트 메서드</h3>
<table>
<thead>
<tr>
<th>메서드</th>
<th>설명</th>
<th>예시</th>
</tr>
</thead>
<tbody><tr>
<td><code>append(x)</code></td>
<td>리스트 끝에 요소 추가</td>
<td><code>a.append(3)</code> → <code>[1, 2, 3]</code></td>
</tr>
<tr>
<td><code>insert(i, x)</code></td>
<td>특정 위치(i)에 요소 추가</td>
<td><code>a.insert(1, 10)</code> → <code>[1, 10, 2, 3]</code></td>
</tr>
<tr>
<td><code>remove(x)</code></td>
<td>첫 번째로 발견된 x 제거</td>
<td><code>a.remove(2)</code> → <code>[1, 3]</code></td>
</tr>
<tr>
<td><code>pop(i)</code></td>
<td>i번째 요소 반환 후 삭제 (기본값: 마지막 요소)</td>
<td><code>a.pop()</code> → <code>[1, 2]</code></td>
</tr>
<tr>
<td><code>sort()</code></td>
<td>오름차순 정렬 (내림차순: <code>reverse=True</code>)</td>
<td><code>a.sort()</code> → <code>[1, 2, 3]</code></td>
</tr>
<tr>
<td><code>reverse()</code></td>
<td>리스트 순서 반전</td>
<td><code>a.reverse()</code> → <code>[3, 2, 1]</code></td>
</tr>
<tr>
<td><code>count(x)</code></td>
<td>특정 요소 개수 반환</td>
<td><code>a.count(2)</code> → <code>1</code></td>
</tr>
<tr>
<td><code>index(x)</code></td>
<td>특정 요소의 첫 번째 위치 반환</td>
<td><code>a.index(2)</code> → <code>1</code></td>
</tr>
</tbody></table>
<hr>
<h2 id="3-튜플-tuple">3. 튜플 (Tuple)</h2>
<ul>
<li>리스트와 유사하지만 <strong>변경 불가능(immutable)</strong></li>
<li>소괄호 <code>()</code>를 사용하여 정의</li>
<li>속도가 빠르고, 변경이 필요 없는 데이터 저장에 적합</li>
</ul>
<h3 id="3-1-튜플-주요-메서드">3-1. 튜플 주요 메서드</h3>
<table>
<thead>
<tr>
<th>메서드</th>
<th>설명</th>
<th>예시</th>
</tr>
</thead>
<tbody><tr>
<td><code>count(x)</code></td>
<td>특정 요소 개수 반환</td>
<td><code>(1,2,2,3).count(2)</code> → <code>2</code></td>
</tr>
<tr>
<td><code>index(x)</code></td>
<td>특정 요소의 첫 번째 위치 반환</td>
<td><code>(1,2,3).index(2)</code> → <code>1</code></td>
</tr>
</tbody></table>
<hr>
<h2 id="4-세트-set">4. 세트 (Set)</h2>
<ul>
<li><strong>중복을 허용하지 않는</strong> 자료형</li>
<li>중괄호 <code>{}</code>를 사용하여 정의 (딕셔너리와 차이점: key-value가 없음)</li>
<li>순서가 없으므로 <strong>인덱싱 불가</strong></li>
</ul>
<h3 id="4-1-세트-주요-메서드">4-1. 세트 주요 메서드</h3>
<table>
<thead>
<tr>
<th>메서드</th>
<th>설명</th>
<th>예시</th>
</tr>
</thead>
<tbody><tr>
<td><code>add(x)</code></td>
<td>요소 추가</td>
<td><code>s.add(3)</code> → <code>{1, 2, 3}</code></td>
</tr>
<tr>
<td><code>remove(x)</code></td>
<td>요소 제거 (없으면 오류 발생)</td>
<td><code>s.remove(2)</code> → <code>{1, 3}</code></td>
</tr>
<tr>
<td><code>discard(x)</code></td>
<td>요소 제거 (없어도 오류 발생 X)</td>
<td><code>s.discard(2)</code></td>
</tr>
<tr>
<td><code>pop()</code></td>
<td>임의의 요소 반환 후 제거</td>
<td><code>s.pop()</code> → <code>1</code></td>
</tr>
<tr>
<td><code>clear()</code></td>
<td>모든 요소 제거</td>
<td><code>s.clear()</code> → <code>{}</code></td>
</tr>
<tr>
<td><code>union(set2)</code></td>
<td>합집합</td>
<td><code>{1,2}.union({2,3})</code> → <code>{1,2,3}</code></td>
</tr>
<tr>
<td><code>intersection(set2)</code></td>
<td>교집합</td>
<td><code>{1,2}.intersection({2,3})</code> → <code>{2}</code></td>
</tr>
<tr>
<td><code>difference(set2)</code></td>
<td>차집합</td>
<td><code>{1,2}.difference({2,3})</code> → <code>{1}</code></td>
</tr>
</tbody></table>
<hr>
<h2 id="5-딕셔너리-dictionary">5. 딕셔너리 (Dictionary)</h2>
<ul>
<li><strong>키(key)와 값(value)</strong> 형태로 데이터를 저장하는 자료형</li>
<li>중괄호 <code>{}</code>를 사용하여 정의</li>
<li><strong>키는 중복 불가</strong>, 값은 중복 가능</li>
<li>키를 통해 데이터를 빠르게 찾을 수 있음</li>
</ul>
<h3 id="5-1-딕셔너리-주요-메서드">5-1. 딕셔너리 주요 메서드</h3>
<table>
<thead>
<tr>
<th>메서드</th>
<th>설명</th>
<th>예시</th>
</tr>
</thead>
<tbody><tr>
<td><code>keys()</code></td>
<td>모든 키 반환</td>
<td><code>d.keys()</code> → <code>dict_keys([&quot;a&quot;, &quot;b&quot;])</code></td>
</tr>
<tr>
<td><code>values()</code></td>
<td>모든 값 반환</td>
<td><code>d.values()</code> → <code>dict_values([1, 2])</code></td>
</tr>
<tr>
<td><code>items()</code></td>
<td>(키, 값) 쌍 반환</td>
<td><code>d.items()</code> → <code>dict_items([(&quot;a&quot;,1), (&quot;b&quot;,2)])</code></td>
</tr>
<tr>
<td><code>get(key, default)</code></td>
<td>키에 해당하는 값 반환 (없으면 default 반환)</td>
<td><code>d.get(&quot;a&quot;)</code> → <code>1</code></td>
</tr>
<tr>
<td><code>pop(key)</code></td>
<td>키에 해당하는 값 반환 후 삭제</td>
<td><code>d.pop(&quot;a&quot;)</code> → <code>{ &quot;b&quot;: 2 }</code></td>
</tr>
<tr>
<td><code>update(dict2)</code></td>
<td>다른 딕셔너리와 병합</td>
<td><code>d.update({&quot;c&quot;:3})</code> → <code>{ &quot;a&quot;:1, &quot;b&quot;:2, &quot;c&quot;:3 }</code></td>
</tr>
<tr>
<td><code>clear()</code></td>
<td>모든 요소 삭제</td>
<td><code>d.clear()</code> → <code>{}</code></td>
</tr>
</tbody></table>
<hr>
<h2 id="6-자료형-비교">6. 자료형 비교</h2>
<table>
<thead>
<tr>
<th>자료형</th>
<th>선언</th>
<th>순서 보장</th>
<th>중복 허용</th>
<th>접근 방식</th>
<th>수정 가능 여부</th>
<th>추가 가능 여부</th>
<th>삭제 가능 여부</th>
</tr>
</thead>
<tbody><tr>
<td>리스트</td>
<td><code>[]</code></td>
<td>O</td>
<td>O</td>
<td>인덱스</td>
<td>O</td>
<td>O</td>
<td>O</td>
</tr>
<tr>
<td>튜플</td>
<td><code>()</code></td>
<td>O</td>
<td>O</td>
<td>인덱스</td>
<td>X</td>
<td>X</td>
<td>X</td>
</tr>
<tr>
<td>세트</td>
<td><code>{}</code></td>
<td>X</td>
<td>X</td>
<td>인덱싱 불가</td>
<td>O</td>
<td>O</td>
<td>O</td>
</tr>
<tr>
<td>딕셔너리</td>
<td><code>{key: value}</code></td>
<td>3.7+ O</td>
<td>키 X / 값 O</td>
<td>키 이용</td>
<td>O</td>
<td>O</td>
<td>O</td>
</tr>
<tr>
<td>- <strong>리스트</strong>: 순서가 있고, 수정 가능</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>- <strong>튜플</strong>: 순서가 있지만, 수정 불가</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>- <strong>세트</strong>: 순서 없고, 중복 불가</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>- <strong>딕셔너리</strong>: 키-값 쌍으로 저장하며, 키는 중복 불가</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>-</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>- <strong>자료형 변환</strong></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody></table>
<pre><code>## 1. 자료형 변환

- 한 자료형을 다른 자료형으로 변경하는 것
- 명시적 변환(개발자가 직접 변환)과 암시적 변환(파이썬이 자동 변환)으로 나뉨

## 2. 명시적 자료형 변환

### 2-1. 정수형 변환

- `int(x)`: x를 정수형으로 변환
- 예시:

    ```python
    print(int(3.14))  # 3
    print(int(&quot;10&quot;))  # 10

    ```


### 2-2. 실수형 변환

- `float(x)`: x를 실수형으로 변환
- 예시:

    ```python
    print(float(10))  # 10.0
    print(float(&quot;3.14&quot;))  # 3.14

    ```


### 2-3. 문자열 변환

- `str(x)`: x를 문자열로 변환
- 예시:

    ```python
    print(str(10))  # &quot;10&quot;
    print(str(3.14))  # &quot;3.14&quot;

    ```


### 2-4. 리스트 변환

- `list(x)`: x를 리스트로 변환
- 예시:

    ```python
    print(list(&quot;hello&quot;))  # [&#39;h&#39;, &#39;e&#39;, &#39;l&#39;, &#39;l&#39;, &#39;o&#39;]
    print(list((1, 2, 3)))  # [1, 2, 3]

    ```


### 2-5. 튜플 변환

- `tuple(x)`: x를 튜플로 변환
- 예시:

    ```python
    print(tuple([1, 2, 3]))  # (1, 2, 3)
    print(tuple(&quot;abc&quot;))  # (&#39;a&#39;, &#39;b&#39;, &#39;c&#39;)

    ```


### 2-6. 세트 변환

- `set(x)`: x를 세트로 변환 (중복 제거됨)
- 예시:

    ```python
    print(set([1, 2, 2, 3]))  # {1, 2, 3}
    print(set(&quot;banana&quot;))  # {&#39;b&#39;, &#39;a&#39;, &#39;n&#39;}

    ```


### 2-7. 딕셔너리 변환

- `dict(x)`: x를 딕셔너리로 변환 (키-값 쌍 필요)
- 예시:

    ```python
    print(dict([[&quot;a&quot;, 1], [&quot;b&quot;, 2]]))  # {&#39;a&#39;: 1, &#39;b&#39;: 2}
    print(dict(((&quot;x&quot;, 10), (&quot;y&quot;, 20))))  # {&#39;x&#39;: 10, &#39;y&#39;: 20}

    ```


## 3. 암시적 자료형 변환

- 파이썬이 자동으로 변환하는 경우 (작은 범위 → 큰 범위)
- 예시:

    ```python
    print(10 + 3.5)  # 13.5 (정수 → 실수 변환)
    print(True + 2)  # 3 (Boolean → 정수 변환)

    ```</code></pre>]]></description>
        </item>
        <item>
            <title><![CDATA[주석, 인덱스와 슬라이싱, 문자열]]></title>
            <link>https://velog.io/@data_lover/%EC%A3%BC%EC%84%9D-%EC%9D%B8%EB%8D%B1%EC%8A%A4%EC%99%80-%EC%8A%AC%EB%9D%BC%EC%9D%B4%EC%8B%B1-%EB%AC%B8%EC%9E%90%EC%97%B4</link>
            <guid>https://velog.io/@data_lover/%EC%A3%BC%EC%84%9D-%EC%9D%B8%EB%8D%B1%EC%8A%A4%EC%99%80-%EC%8A%AC%EB%9D%BC%EC%9D%B4%EC%8B%B1-%EB%AC%B8%EC%9E%90%EC%97%B4</guid>
            <pubDate>Wed, 12 Mar 2025 07:39:46 GMT</pubDate>
            <description><![CDATA[<h2 id="1-주석">1. 주석</h2>
<ul>
<li><p>코드의 설명을 위해 사용되며 실행되지 않음</p>
</li>
<li><p>한 줄 주석: <code>#</code> 기호 사용</p>
<ul>
<li>예: <code># 이것은 한 줄 주석입니다.</code></li>
</ul>
</li>
<li><p>여러 줄 주석: 따옴표 세 개(<code>&#39;&#39;&#39;</code> 또는 <code>&quot;&quot;&quot;</code>) 사용</p>
<ul>
<li><p>예:</p>
<pre><code class="language-python">&#39;&#39;&#39;
이것은 여러 줄 주석입니다.
여러 줄에 걸쳐 작성할 수 있습니다.
&#39;&#39;&#39;
</code></pre>
</li>
</ul>
</li>
</ul>
<h2 id="2-인덱스와-슬라이싱">2. 인덱스와 슬라이싱</h2>
<h3 id="2-1-문자열-인덱싱">2-1. 문자열 인덱싱</h3>
<ul>
<li>문자열에서 특정 위치의 문자에 접근하는 방법</li>
<li>인덱스는 0부터 시작하며, 음수 인덱스도 사용 가능<ul>
<li>예: <code>s = &quot;Python&quot;</code><ul>
<li><code>s[0]</code> → <code>&#39;P&#39;</code></li>
<li><code>s[-1]</code> → <code>&#39;n&#39;</code></li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="2-2-문자열-슬라이싱">2-2. 문자열 슬라이싱</h3>
<ul>
<li>문자열의 일부를 추출하는 방법</li>
<li><code>[시작:끝:간격]</code> 형태로 사용하며, 끝 인덱스는 포함되지 않음<ul>
<li>예: <code>s = &quot;Python&quot;</code><ul>
<li><code>s[0:4]</code> → <code>&#39;Pyth&#39;</code></li>
<li><code>s[:3]</code> → <code>&#39;Pyt&#39;</code> (0부터 3 전까지)</li>
<li><code>s[2:]</code> → <code>&#39;thon&#39;</code> (2부터 끝까지)</li>
<li><code>s[::2]</code> → <code>&#39;Pto&#39;</code> (2칸씩 건너뜀)</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="3-문자열-처리">3. 문자열 처리</h2>
<ul>
<li>문자열 연결: <code>+</code> 연산자 사용 (<code>&quot;Hello&quot; + &quot; World&quot; → &quot;Hello World&quot;</code>)</li>
<li>문자열 반복:  연산자 사용 (<code>&quot;Hi&quot; * 3 → &quot;HiHiHi&quot;</code>)</li>
<li>문자열 길이: <code>len()</code> 함수 사용 (<code>len(&quot;Python&quot;) → 6</code>)</li>
</ul>
<h2 id="4-문자열-메서드">4. 문자열 메서드</h2>
<table>
<thead>
<tr>
<th>메서드</th>
<th>설명</th>
<th>예시</th>
</tr>
</thead>
<tbody><tr>
<td><code>upper()</code></td>
<td>문자열을 대문자로 변환</td>
<td><code>&#39;python&#39;.upper()</code> → <code>&#39;PYTHON&#39;</code></td>
</tr>
<tr>
<td><code>lower()</code></td>
<td>문자열을 소문자로 변환</td>
<td><code>&#39;PYTHON&#39;.lower()</code> → <code>&#39;python&#39;</code></td>
</tr>
<tr>
<td><code>strip()</code></td>
<td>앞뒤 공백 제거</td>
<td><code>&#39; hello &#39;.strip()</code> → <code>&#39;hello&#39;</code></td>
</tr>
<tr>
<td><code>replace(a, b)</code></td>
<td>문자열 내 특정 문자(a)를 다른 문자(b)로 변경</td>
<td><code>&#39;apple&#39;.replace(&#39;p&#39;, &#39;b&#39;)</code> → <code>&#39;abble&#39;</code></td>
</tr>
<tr>
<td><code>split(sep)</code></td>
<td>특정 구분자(sep) 기준으로 문자열 분리</td>
<td><code>&#39;a,b,c&#39;.split(&#39;,&#39;)</code> → <code>[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]</code></td>
</tr>
<tr>
<td><code>join(iterable)</code></td>
<td>리스트 등의 요소를 문자열로 결합</td>
<td><code>&#39;-&#39;.join([&#39;a&#39;, &#39;b&#39;, &#39;c&#39;])</code> → <code>&#39;a-b-c&#39;</code></td>
</tr>
<tr>
<td><code>find(sub)</code></td>
<td>특정 문자열(sub)의 위치 반환 (없으면 -1)</td>
<td><code>&#39;hello&#39;.find(&#39;l&#39;)</code> → <code>2</code></td>
</tr>
<tr>
<td><code>count(sub)</code></td>
<td>특정 문자열(sub)의 개수 반환</td>
<td><code>&#39;banana&#39;.count(&#39;a&#39;)</code> → <code>3</code></td>
</tr>
</tbody></table>
<h2 id="5-문자열-포맷">5. 문자열 포맷</h2>
<ul>
<li>문자열 내 변수 값을 삽입하는 방법</li>
<li>다양한 방식이 존재함</li>
</ul>
<h3 id="5-1--기호-사용">5-1. % 기호 사용</h3>
<pre><code class="language-python">name = &quot;Alice&quot;
age = 25
print(&quot;이름: %s, 나이: %d&quot; % (name, age))
# 출력: 이름: Alice, 나이: 25
</code></pre>
<h3 id="5-2-format-함수-사용">5-2. <code>format()</code> 함수 사용</h3>
<pre><code class="language-python">print(&quot;이름: {}, 나이: {}&quot;.format(name, age))
# 출력: 이름: Alice, 나이: 25
</code></pre>
<h3 id="5-3-f-string-사용-파이썬-36-이상">5-3. f-string 사용 (파이썬 3.6 이상)</h3>
<pre><code class="language-python">print(f&quot;이름: {name}, 나이: {age}&quot;)
# 출력: 이름: Alice, 나이: 25
</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[자료형, 변수, 변수 이름, 형 변환]]></title>
            <link>https://velog.io/@data_lover/%EC%9E%90%EB%A3%8C%ED%98%95-%EB%B3%80%EC%88%98-%EB%B3%80%EC%88%98-%EC%9D%B4%EB%A6%84-%ED%98%95-%EB%B3%80%ED%99%98</link>
            <guid>https://velog.io/@data_lover/%EC%9E%90%EB%A3%8C%ED%98%95-%EB%B3%80%EC%88%98-%EB%B3%80%EC%88%98-%EC%9D%B4%EB%A6%84-%ED%98%95-%EB%B3%80%ED%99%98</guid>
            <pubDate>Wed, 12 Mar 2025 07:38:52 GMT</pubDate>
            <description><![CDATA[<h2 id="1-자료형-data-types">1. 자료형 (Data Types)</h2>
<p>1-1. 기본 자료형</p>
<ul>
<li><strong>정수형 (int)</strong>: 소수점이 없는 숫자 (예: 10, -5)</li>
<li><strong>실수형 (float)</strong>: 소수점이 있는 숫자 (예: 3.14, -0.7)</li>
<li><strong>문자열 (str)</strong>: 문자들의 집합 (예: &quot;Hello&quot;, &#39;Python&#39;)</li>
<li><strong>불리언 (bool)</strong>: 참(True)과 거짓(False)을 나타내는 값</li>
</ul>
<p>1-2. 컬렉션 자료형</p>
<ul>
<li><strong>리스트 (list)</strong>: 여러 값을 순서대로 저장하는 자료형 (예: [1, 2, 3])</li>
<li><strong>튜플 (tuple)</strong>: 변경할 수 없는 리스트 (예: (1, 2, 3))</li>
<li><strong>딕셔너리 (dict)</strong>: 키-값 쌍을 저장하는 자료형 (예: {&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25})</li>
<li><strong>집합 (set)</strong>: 중복을 허용하지 않는 자료형 (예: {1, 2, 3})</li>
</ul>
<h2 id="2-변수-variable">2. 변수 (Variable)</h2>
<ul>
<li><p>데이터를 저장하는 공간</p>
</li>
<li><p>변수 선언 방식: <code>변수명 = 값</code></p>
</li>
<li><p>예제:</p>
<pre><code class="language-python">  age = 25
  name = &quot;Alice&quot;
  height = 170.5
</code></pre>
</li>
<li><p>변수의 자료형은 동적으로 결정됨 (동적 타이핑)</p>
</li>
</ul>
<h2 id="3-변수-이름-variable-naming">3. 변수 이름 (Variable Naming)</h2>
<p>3-1. 변수 이름 규칙</p>
<ul>
<li>영문자, 숫자, 밑줄(_)만 사용 가능</li>
<li>숫자로 시작할 수 없음</li>
<li>대소문자를 구분함 (예: <code>Name</code>과 <code>name</code>은 다른 변수)</li>
<li>파이썬 키워드는 사용 불가 (예: <code>if</code>, <code>while</code>, <code>def</code> 등)</li>
</ul>
<p>3-2. 변수 이름 스타일</p>
<ul>
<li><strong>스네이크 케이스 (snake_case)</strong>: 여러 단어를 밑줄(_)로 구분 (예: <code>user_name</code>)</li>
<li><strong>카멜 케이스 (camelCase)</strong>: 첫 단어는 소문자, 이후 단어는 대문자로 시작 (예: <code>userName</code>)</li>
<li><strong>파스칼 케이스 (PascalCase)</strong>: 모든 단어의 첫 글자를 대문자로 (예: <code>UserName</code>)</li>
</ul>
<h2 id="4-형-변환-type-casting">4. 형 변환 (Type Casting)</h2>
<ul>
<li><p>한 자료형을 다른 자료형으로 변환하는 과정</p>
</li>
<li><p>주요 함수:</p>
<ul>
<li><code>int()</code>: 정수로 변환</li>
<li><code>float()</code>: 실수로 변환</li>
<li><code>str()</code>: 문자열로 변환</li>
<li><code>bool()</code>: 불리언 값으로 변환</li>
</ul>
</li>
<li><p>예제:</p>
<pre><code class="language-python">  num_str = &quot;100&quot;
  num_int = int(num_str)  # 문자열을 정수로 변환
  num_float = float(num_int)  # 정수를 실수로 변환
</code></pre>
</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[Pandas7_1]]></title>
            <link>https://velog.io/@data_lover/Pandas71</link>
            <guid>https://velog.io/@data_lover/Pandas71</guid>
            <pubDate>Wed, 12 Mar 2025 07:29:45 GMT</pubDate>
            <description><![CDATA[<h1 id="다중-인덱스">다중 인덱스</h1>
<h2 id="1-시리즈-계층-인덱싱">1. 시리즈 계층 인덱싱</h2>
<h3 id="다중-인덱스-사용-시리즈">다중 인덱스 사용 시리즈</h3>
<ul>
<li>다중 인덱스(MultiIndex)는 여러 단계로 구성된 인덱스를 의미하며, 계층적으로 데이터를 관리할 수 있음.</li>
<li><code>pd.Series</code>에서 다중 인덱스를 생성할 때 <code>pd.MultiIndex.from_tuples()</code>를 사용함.</li>
<li>다중 인덱스를 활용하면 그룹별 데이터를 보다 직관적으로 표현할 수 있음.</li>
</ul>
<p><strong>기본 코드:</strong></p>
<pre><code class="language-python">import pandas as pd
import numpy as np

index = pd.MultiIndex.from_tuples([(&#39;A&#39;, 1), (&#39;A&#39;, 2), (&#39;B&#39;, 1), (&#39;B&#39;, 2)])
s = pd.Series([10, 20, 30, 40], index=index)
print(s)
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>A  1    10
   2    20
B  1    30
   2    40
dtype: int64
</code></pre><h3 id="시리즈-인덱싱--슬라이싱">시리즈 인덱싱 &amp; 슬라이싱</h3>
<h3 id="0-레벨-인덱싱">0-레벨 인덱싱</h3>
<ul>
<li>최상위 레벨의 값을 기준으로 슬라이싱 가능.</li>
</ul>
<pre><code class="language-python">print(s[&#39;A&#39;])
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>1    10
2    20
dtype: int64
</code></pre><h3 id="0-레벨과-1-레벨-동시-인덱싱-loc-속성-사용">0-레벨과 1-레벨 동시 인덱싱 (<code>loc</code> 속성 사용)</h3>
<ul>
<li>특정 레벨 값을 함께 지정하여 접근 가능.</li>
</ul>
<pre><code class="language-python">print(s.loc[&#39;A&#39;, 1])
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>10
</code></pre><h3 id="팬시-인덱싱">팬시 인덱싱</h3>
<ul>
<li>여러 개의 값을 한 번에 선택 가능.</li>
</ul>
<pre><code class="language-python">print(s.loc[[&#39;A&#39;, &#39;B&#39;]])
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>A  1    10
   2    20
B  1    30
   2    40
dtype: int64
</code></pre><hr>
<h2 id="2-스택과-언스택">2. 스택과 언스택</h2>
<h3 id="스택stack">스택(Stack)</h3>
<ul>
<li>다중 인덱스를 컬럼에서 행 인덱스로 변환하는 과정.</li>
</ul>
<pre><code class="language-python">df = s.unstack()
print(df)
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>     1   2
A   10  20
B   30  40
</code></pre><h3 id="언스택unstack">언스택(Unstack)</h3>
<ul>
<li>행 인덱스를 다시 컬럼으로 변환하는 과정.</li>
</ul>
<pre><code class="language-python">print(df.stack())
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>A  1    10
   2    20
B  1    30
   2    40
dtype: int64
</code></pre><hr>
<h2 id="3-데이터프레임-계층-인덱싱">3. 데이터프레임 계층 인덱싱</h2>
<h3 id="다중-행열-인덱스-사용">다중 행/열 인덱스 사용</h3>
<ul>
<li><code>pd.MultiIndex.from_product()</code>를 사용하여 다중 행 및 열 인덱스를 생성할 수 있음.</li>
</ul>
<pre><code class="language-python">columns = pd.MultiIndex.from_product([[&#39;X&#39;, &#39;Y&#39;], [&#39;A&#39;, &#39;B&#39;]])
df = pd.DataFrame(np.arange(16).reshape(4, 4), index=index, columns=columns)
print(df)
</code></pre>
<hr>
<h2 id="4-다중-인덱스-레벨-교환과-정렬">4. 다중 인덱스 레벨 교환과 정렬</h2>
<h3 id="레벨-교환">레벨 교환</h3>
<ul>
<li><code>swaplevel()</code>을 사용하여 인덱스의 레벨을 교환할 수 있음.</li>
</ul>
<pre><code class="language-python">print(df.swaplevel())
</code></pre>
<h3 id="인덱스-라벨-정렬">인덱스 라벨 정렬</h3>
<ul>
<li><code>sort_index()</code>를 사용하여 정렬 가능.</li>
</ul>
<pre><code class="language-python">print(df.sort_index())
</code></pre>
<hr>
<h2 id="5-레벨-단위-그룹화">5. 레벨 단위 그룹화</h2>
<ul>
<li><code>groupby(level=0)</code>을 사용하여 특정 레벨 기준으로 그룹화 가능.</li>
</ul>
<pre><code class="language-python">print(df.groupby(level=0).sum())
</code></pre>
<hr>
<h2 id="6-인덱스-지정과-초기화">6. 인덱스 지정과 초기화</h2>
<h3 id="set_index-메소드"><code>set_index()</code> 메소드</h3>
<ul>
<li>특정 열을 인덱스로 설정 가능.</li>
</ul>
<pre><code class="language-python">df = pd.DataFrame({&#39;A&#39;: [&#39;foo&#39;, &#39;bar&#39;, &#39;baz&#39;], &#39;B&#39;: [1, 2, 3]})
df.set_index(&#39;A&#39;, inplace=True)
print(df)
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>     B
A
foo  1
bar  2
baz  3
</code></pre><h3 id="reset_index-메소드"><code>reset_index()</code> 메소드</h3>
<ul>
<li>기존 인덱스를 제거하고 열로 변환.</li>
</ul>
<pre><code class="language-python">df.reset_index(inplace=True)
print(df)
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>     A  B
0  foo  1
1  bar  2
2  baz  3
</code></pre><h3 id="droptrue-옵션"><code>drop=True</code> 옵션</h3>
<ul>
<li>인덱스를 삭제하고 열로 변환하지 않음.</li>
</ul>
<pre><code class="language-python">df.reset_index(drop=True, inplace=True)
print(df)
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>   B
0  1
1  2
2  3
</code></pre><hr>
<h1 id="데이터-그룹화">데이터 그룹화</h1>
<h2 id="1-개요">1. 개요</h2>
<ul>
<li><p>데이터 그룹화는 데이터를 특정 기준으로 묶어서 분석하는 기법임.</p>
</li>
<li><p><code>groupby()</code> 메소드를 사용하여 그룹을 생성하고, 다양한 집계 함수를 적용할 수 있음.</p>
<hr>
</li>
</ul>
<h2 id="2-시리즈-그룹화">2. 시리즈 그룹화</h2>
<h3 id="value_counts-메소드"><code>value_counts()</code> 메소드</h3>
<ul>
<li>특정 값의 개수를 계산할 때 사용.</li>
</ul>
<pre><code class="language-python">s = pd.Series([&#39;A&#39;, &#39;B&#39;, &#39;A&#39;, &#39;C&#39;, &#39;B&#39;, &#39;A&#39;])
print(s.value_counts())
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>A    3
B    2
C    1
dtype: int64
</code></pre><h3 id="mean-메소드"><code>mean()</code> 메소드</h3>
<ul>
<li>그룹별 평균 값을 구함.</li>
</ul>
<pre><code class="language-python">df = pd.DataFrame({&#39;Category&#39;: [&#39;A&#39;, &#39;B&#39;, &#39;A&#39;, &#39;B&#39;], &#39;Value&#39;: [10, 20, 30, 40]})
print(df.groupby(&#39;Category&#39;)[&#39;Value&#39;].mean())
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>Category
A    20.0
B    30.0
Name: Value, dtype: float64
</code></pre><hr>
<h2 id="3-데이터프레임-그룹화">3. 데이터프레임 그룹화</h2>
<h3 id="다중-키-활용-그룹화">다중 키 활용 그룹화</h3>
<ul>
<li>두 개 이상의 키를 기준으로 그룹화 가능.</li>
</ul>
<pre><code class="language-python">print(df.groupby([&#39;Category&#39;, &#39;Value&#39;]).count())
</code></pre>
<h3 id="dropna-키워드-인자"><code>dropna</code> 키워드 인자</h3>
<ul>
<li><code>dropna=True</code>: 결측값이 있는 그룹을 제거</li>
<li><code>dropna=False</code>: 결측값이 있는 그룹도 유지</li>
</ul>
<h3 id="count-집계-함수"><code>count()</code> 집계 함수</h3>
<pre><code class="language-python">print(df.groupby(&#39;Category&#39;).count())
</code></pre>
<hr>
<h2 id="4-그룹-확인">4. 그룹 확인</h2>
<h3 id="for-반복문-활용"><code>for</code> 반복문 활용</h3>
<pre><code class="language-python">for name, group in df.groupby(&#39;Category&#39;):
    print(name)
    print(group)
</code></pre>
<hr>
<h2 id="5-열-선택-및-함수-활용-그룹화">5. 열 선택 및 함수 활용 그룹화</h2>
<ul>
<li>특정 열을 기준으로 그룹화할 수 있으며, 시리즈나 사전을 활용할 수 있음.</li>
</ul>
<pre><code class="language-python">print(df.groupby(&#39;Category&#39;)[&#39;Value&#39;].sum())
</code></pre>
<hr>
<h2 id="6-멀티-인덱스-레벨-활용">6. 멀티 인덱스 레벨 활용</h2>
<ul>
<li>행과 열 모두를 기준으로 그룹화 가능.</li>
</ul>
<pre><code class="language-python">print(df.groupby([&#39;Category&#39;, &#39;Value&#39;]).sum())
</code></pre>
<hr>
]]></description>
        </item>
        <item>
            <title><![CDATA[Pandas6]]></title>
            <link>https://velog.io/@data_lover/Pandas6</link>
            <guid>https://velog.io/@data_lover/Pandas6</guid>
            <pubDate>Wed, 12 Mar 2025 07:28:30 GMT</pubDate>
            <description><![CDATA[<h1 id="다중-인덱스">다중 인덱스</h1>
<h2 id="1-시리즈-계층-인덱싱">1. 시리즈 계층 인덱싱</h2>
<h3 id="다중-인덱스-사용-시리즈">다중 인덱스 사용 시리즈</h3>
<ul>
<li>다중 인덱스(MultiIndex)는 여러 단계로 구성된 인덱스를 의미하며, 계층적으로 데이터를 관리할 수 있음.</li>
<li><code>pd.Series</code>에서 다중 인덱스를 생성할 때 <code>pd.MultiIndex.from_tuples()</code>를 사용함.</li>
<li>다중 인덱스를 활용하면 그룹별 데이터를 보다 직관적으로 표현할 수 있음.</li>
</ul>
<p><strong>기본 코드:</strong></p>
<pre><code class="language-python">import pandas as pd
import numpy as np

index = pd.MultiIndex.from_tuples([(&#39;A&#39;, 1), (&#39;A&#39;, 2), (&#39;B&#39;, 1), (&#39;B&#39;, 2)])
s = pd.Series([10, 20, 30, 40], index=index)
print(s)
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>A  1    10
   2    20
B  1    30
   2    40
dtype: int64
</code></pre><h3 id="시리즈-인덱싱--슬라이싱">시리즈 인덱싱 &amp; 슬라이싱</h3>
<h3 id="0-레벨-인덱싱">0-레벨 인덱싱</h3>
<ul>
<li>최상위 레벨의 값을 기준으로 슬라이싱 가능.</li>
</ul>
<pre><code class="language-python">print(s[&#39;A&#39;])
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>1    10
2    20
dtype: int64
</code></pre><h3 id="0-레벨과-1-레벨-동시-인덱싱-loc-속성-사용">0-레벨과 1-레벨 동시 인덱싱 (<code>loc</code> 속성 사용)</h3>
<ul>
<li>특정 레벨 값을 함께 지정하여 접근 가능.</li>
</ul>
<pre><code class="language-python">print(s.loc[&#39;A&#39;, 1])
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>10
</code></pre><h3 id="팬시-인덱싱">팬시 인덱싱</h3>
<ul>
<li>여러 개의 값을 한 번에 선택 가능.</li>
</ul>
<pre><code class="language-python">print(s.loc[[&#39;A&#39;, &#39;B&#39;]])
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>A  1    10
   2    20
B  1    30
   2    40
dtype: int64
</code></pre><hr>
<h2 id="2-스택과-언스택">2. 스택과 언스택</h2>
<h3 id="스택stack">스택(Stack)</h3>
<ul>
<li>다중 인덱스를 컬럼에서 행 인덱스로 변환하는 과정.</li>
</ul>
<pre><code class="language-python">df = s.unstack()
print(df)
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>     1   2
A   10  20
B   30  40
</code></pre><h3 id="언스택unstack">언스택(Unstack)</h3>
<ul>
<li>행 인덱스를 다시 컬럼으로 변환하는 과정.</li>
</ul>
<pre><code class="language-python">print(df.stack())
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>A  1    10
   2    20
B  1    30
   2    40
dtype: int64
</code></pre><hr>
<h2 id="3-데이터프레임-계층-인덱싱">3. 데이터프레임 계층 인덱싱</h2>
<h3 id="다중-행열-인덱스-사용">다중 행/열 인덱스 사용</h3>
<ul>
<li><code>pd.MultiIndex.from_product()</code>를 사용하여 다중 행 및 열 인덱스를 생성할 수 있음.</li>
</ul>
<pre><code class="language-python">columns = pd.MultiIndex.from_product([[&#39;X&#39;, &#39;Y&#39;], [&#39;A&#39;, &#39;B&#39;]])
df = pd.DataFrame(np.arange(16).reshape(4, 4), index=index, columns=columns)
print(df)
</code></pre>
<hr>
<h2 id="4-다중-인덱스-레벨-교환과-정렬">4. 다중 인덱스 레벨 교환과 정렬</h2>
<h3 id="레벨-교환">레벨 교환</h3>
<ul>
<li><code>swaplevel()</code>을 사용하여 인덱스의 레벨을 교환할 수 있음.</li>
</ul>
<pre><code class="language-python">print(df.swaplevel())
</code></pre>
<h3 id="인덱스-라벨-정렬">인덱스 라벨 정렬</h3>
<ul>
<li><code>sort_index()</code>를 사용하여 정렬 가능.</li>
</ul>
<pre><code class="language-python">print(df.sort_index())
</code></pre>
<hr>
<h2 id="5-레벨-단위-그룹화">5. 레벨 단위 그룹화</h2>
<ul>
<li><code>groupby(level=0)</code>을 사용하여 특정 레벨 기준으로 그룹화 가능.</li>
</ul>
<pre><code class="language-python">print(df.groupby(level=0).sum())
</code></pre>
<hr>
<h2 id="6-인덱스-지정과-초기화">6. 인덱스 지정과 초기화</h2>
<h3 id="set_index-메소드"><code>set_index()</code> 메소드</h3>
<ul>
<li>특정 열을 인덱스로 설정 가능.</li>
</ul>
<pre><code class="language-python">df = pd.DataFrame({&#39;A&#39;: [&#39;foo&#39;, &#39;bar&#39;, &#39;baz&#39;], &#39;B&#39;: [1, 2, 3]})
df.set_index(&#39;A&#39;, inplace=True)
print(df)
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>     B
A
foo  1
bar  2
baz  3
</code></pre><h3 id="reset_index-메소드"><code>reset_index()</code> 메소드</h3>
<ul>
<li>기존 인덱스를 제거하고 열로 변환.</li>
</ul>
<pre><code class="language-python">df.reset_index(inplace=True)
print(df)
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>     A  B
0  foo  1
1  bar  2
2  baz  3
</code></pre><h3 id="droptrue-옵션"><code>drop=True</code> 옵션</h3>
<ul>
<li>인덱스를 삭제하고 열로 변환하지 않음.</li>
</ul>
<pre><code class="language-python">df.reset_index(drop=True, inplace=True)
print(df)
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>   B
0  1
1  2
2  3
</code></pre><hr>
<h2 id="7-모양-변환의-항목-재배열">7. 모양 변환의 항목 재배열</h2>
<h3 id="스택과-언스택">스택과 언스택</h3>
<ul>
<li><code>dropna=False</code> 옵션을 사용하면 NaN 값도 유지됨.</li>
</ul>
<pre><code class="language-python">print(df.stack(dropna=False))
</code></pre>
<hr>
<h2 id="8-테이블-데이터셋에서-긴-형태의-데이터-프레임-생성">8. 테이블 데이터셋에서 긴 형태의 데이터 프레임 생성</h2>
<ul>
<li><code>pop()</code> 메소드 사용 시 주의해야 함.</li>
</ul>
<pre><code class="language-python">df[&#39;C&#39;] = [10, 20, 30]
removed_column = df.pop(&#39;C&#39;)
print(df)
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>     A  B
0  foo  1
1  bar  2
2  baz  3
</code></pre><hr>
<h2 id="9-피버팅과-언피버팅">9. 피버팅과 언피버팅</h2>
<h3 id="피버팅-pivot">피버팅 (<code>pivot()</code>)</h3>
<ul>
<li>하나 또는 두 개의 열을 기준으로 변환 가능.</li>
</ul>
<pre><code class="language-python">df = pd.DataFrame({&#39;A&#39;: [&#39;X&#39;, &#39;X&#39;, &#39;Y&#39;, &#39;Y&#39;], &#39;B&#39;: [1, 2, 1, 2], &#39;C&#39;: [10, 20, 30, 40]})
pivot_df = df.pivot(index=&#39;A&#39;, columns=&#39;B&#39;, values=&#39;C&#39;)
print(pivot_df)
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>B   1   2
A
X  10  20
Y  30  40
</code></pre><h3 id="pdmelt-함수"><code>pd.melt()</code> 함수</h3>
<ul>
<li><code>id_vars</code> 키워드 인자를 활용하여 변환.</li>
</ul>
<pre><code class="language-python">melted_df = pd.melt(df, id_vars=[&#39;A&#39;])
print(melted_df)
</code></pre>
<p><strong>출력:</strong></p>
<pre><code>   A variable  value
0  X        B      1
1  X        B      2
2  Y        B      1
3  Y        B      2
4  X        C     10
5  X        C     20
6  Y        C     30
7  Y        C     40
</code></pre><h3 id="pivot과-unstack-비교"><code>pivot()</code>과 <code>unstack()</code> 비교</h3>
<ul>
<li><code>set_index()</code>와 <code>unstack()</code>을 연속 적용한 결과와 동일함.</li>
</ul>
<pre><code class="language-python">print(df.set_index([&#39;A&#39;, &#39;B&#39;]).unstack())
</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[Pandas5]]></title>
            <link>https://velog.io/@data_lover/Pandas5</link>
            <guid>https://velog.io/@data_lover/Pandas5</guid>
            <pubDate>Wed, 12 Mar 2025 07:27:35 GMT</pubDate>
            <description><![CDATA[<h1 id="데이터-결합합병">데이터 결합/합병</h1>
<h2 id="1데이터-결합">1.데이터 결합</h2>
<h3 id="pdconact-함수"><code>pd.conact()</code> 함수</h3>
<p>Pandas 라이브러리에서 여러 DataFrame 또는 Series를 연결(concatenate)행(row) 또는 열(column) 단위로 데이터를 합칠 수 있습니다.</p>
<pre><code class="language-python">import pandas as pd

# 예시 DataFrame
df1 = pd.DataFrame({&#39;A&#39;: [1, 2], &#39;B&#39;: [3, 4]})
df2 = pd.DataFrame({&#39;A&#39;: [5, 6], &#39;B&#39;: [7, 8]})

# 행 방향으로 연결 (기본 axis=0)
result = pd.concat([df1, df2])
print(result)</code></pre>
<ul>
<li><p>주요 인자</p>
<ol>
<li><strong>objs</strong>: 합칠 객체들의 리스트. 이 객체들은 DataFrame 또는 Series여야 합니다.</li>
<li><strong>axis</strong>: 연결할 축을 지정합니다. <code>axis=0</code>은 행 방향으로 연결, <code>axis=1</code>은 열 방향으로 연결합니다. 기본값은 <code>axis=0</code>입니다.</li>
<li><strong>ignore_index</strong>: True로 설정하면 인덱스를 무시하고 새로 생성된 인덱스를 할당합니다. 기본값은 False입니다.</li>
<li><strong>keys</strong>: 여러 DataFrame을 합칠 때 각 DataFrame에 대한 레벨을 지정할 수 있습니다. MultiIndex를 생성할 수 있습니다.</li>
<li><strong>join</strong>: <code>inner</code> 또는 <code>outer</code>를 지정할 수 있습니다. <code>outer</code>는 모든 열을 포함, <code>inner</code>는 공통 열만 포함하여 합칩니다. 기본값은 <code>outer</code>입니다.</li>
<li><strong>verify_integrity</strong>: True로 설정하면, 중복된 인덱스를 체크하고 오류를 발생시킵니다.</li>
</ol>
</li>
<li><p><strong>행 방향 연결 (<code>axis=0</code>)</strong></p>
</li>
</ul>
<pre><code class="language-python">df1 = pd.DataFrame({&#39;A&#39;: [1, 2], &#39;B&#39;: [3, 4]})
df2 = pd.DataFrame({&#39;A&#39;: [5, 6], &#39;B&#39;: [7, 8]})

# 두 DataFrame을 행 방향으로 합치기
result = pd.concat([df1, df2], ignore_index=True)
print(result)</code></pre>
<pre><code>   A  B
0  1  3
1  2  4
2  5  7
3  6  8</code></pre><ul>
<li><strong>열 방향 연결 (<code>axis=1</code>)</strong></li>
</ul>
<pre><code class="language-python">df1 = pd.DataFrame({&#39;A&#39;: [1, 2]})
df2 = pd.DataFrame({&#39;B&#39;: [3, 4]})

# 두 DataFrame을 열 방향으로 합치기
result = pd.concat([df1, df2], axis=1)
print(result)</code></pre>
<pre><code>   A  B
0  1  3
1  2  4</code></pre>]]></description>
        </item>
        <item>
            <title><![CDATA[Pandas4]]></title>
            <link>https://velog.io/@data_lover/Pandas4</link>
            <guid>https://velog.io/@data_lover/Pandas4</guid>
            <pubDate>Wed, 12 Mar 2025 07:26:47 GMT</pubDate>
            <description><![CDATA[<h1 id="판다스-활용-기초-통계">판다스 활용: 기초 통계</h1>
<h3 id="기본-설정"><strong>기본 설정</strong></h3>
<p><code>pandas</code> 라이브러리는 보통 <code>pd</code> 라는 별칭으로 사용됨.</p>
<pre><code class="language-python">import pandas as pd
import numpy as np</code></pre>
<p>랜덤 시드, 어레이 내부에 사용되는 부동소수점 정확도, 도표 크기 지정 옵션 등은 이전과 동일함.</p>
<pre><code class="language-python">np.random.seed(12345)
np.set_printoptions(precision=4, suppress=True)

import matplotlib.pyplot as plt
plt.rc(&#39;figure&#39;, figsize=(10, 6))</code></pre>
<hr>
<p><code>Series</code>와 <code>DataFrame</code>을 표로 보여줄 때 사용되는 행의 수를 20으로 지정함.</p>
<p><strong>기본값=60</strong></p>
<pre><code class="language-python">pd.options.display.max_rows # 원래 60이 기본.</code></pre>
<p>기본값(60)을 20으로 변경함.</p>
<pre><code class="language-python">pd.set_option(&quot;display.max_rows&quot;,20)</code></pre>
<hr>
<h3 id="데이터-탐색"><strong>데이터 탐색</strong></h3>
<p>주요 메서드</p>
<ul>
<li><code>head()</code></li>
<li><code>tail()</code></li>
<li><code>info()</code></li>
</ul>
<hr>
<p>예시를 위한 아래 데이터프레임 이용</p>
<pre><code class="language-python">dict = {&#39;state&#39;: [&#39;Ohio&#39;, &#39;Ohio&#39;, &#39;Ohio&#39;, &#39;Nevada&#39;, &#39;Nevada&#39;, &#39;Nevada&#39;, &#39;NY&#39;, &#39;NY&#39;, &#39;NY&#39;],
         &#39;year&#39;: [str(num) for num in [2000, 2001, 2002, 2001, 2002, 2003, 2002, 2003, 2004]],
         &#39;pop&#39;: [1.5, 1.7, 3.6, 2.4, 2.9, 3.2, 8.3, 8.4, 8.5],
         &#39;debt&#39;:np.linspace(0, 1, 9)}

frame = pd.DataFrame(dict, columns=[&#39;year&#39;, &#39;state&#39;, &#39;pop&#39;, &#39;debt&#39;],
                      index=[&#39;one&#39;, &#39;two&#39;, &#39;three&#39;, &#39;four&#39;,
                             &#39;five&#39;, &#39;six&#39;, &#39;seven&#39;, &#39;eight&#39;, &#39;nine&#39;])
frame</code></pre>
<pre><code>       year     state     pop     debt
one     2000    Ohio      1.5     0.000
two     2001    Ohio      1.7     0.125
three2002    Ohio      3.6     0.250
four 2001    Nevada    2.4     0.375
five 2002    Nevada    2.9     0.500
six     2003    Nevada    3.2     0.625
seven2002    NY        8.3     0.750
eight2003    NY        8.4     0.875
nine 2004    NY        8.5     1.000

#표 형태임.</code></pre><hr>
<p><strong><code>head()</code> 메서드</strong></p>
<p><code>head()</code> 메서드는 지정된 크기만큼의 행을 보여줌. </p>
<p>인자를 지정하지 않으면 처음 5개의 행을 보여줌.</p>
<pre><code class="language-python">frame.head() #처음_5개행만
frame.head(3)</code></pre>
<hr>
<p><strong><code>tail()</code> 메서드</strong></p>
<p><code>tail()</code> 메서드는 지정된 크기만큼의 행을 뒤에서부터 보여줌.</p>
<p>인자를 지정하지 않으면 뒤에서부터 5개의 행을 보여줌.</p>
<pre><code class="language-python">frame.tail() #마지막부터_5개행만
frame.tail(3)</code></pre>
<hr>
<p><strong><code>info()</code> 메서드</strong></p>
<p>열(columns) 별로 결측치가 아닌 항목의 수와 자료형을 확인해줌.</p>
<ul>
<li><code>9 non-null</code>: 결측치가 아닌 항목이 9개 있음을 의미함.</li>
<li><code>object</code>: 일반적으로 문자열 자료형을 가리킴.</li>
</ul>
<pre><code class="language-python">frame.info()</code></pre>
<pre><code>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;
Index: 9 entries, one to nine
Data columns (total 4 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   year    9 non-null      object 
 1   state   9 non-null      object 
 2   pop     9 non-null      float64
 3   debt    9 non-null      float64
dtypes: float64(2), object(2)
memory usage: 360.0+ bytes</code></pre><hr>
<h3 id="합-평균-표준편차"><strong>합, 평균, 표준편차</strong></h3>
<p>기초 통계에서 사용되는 주요 메서드</p>
<ul>
<li><code>sum()</code></li>
<li><code>mean()</code></li>
<li><code>std()</code></li>
<li><code>idxmax()</code>/<code>idxmin()</code></li>
<li><code>cumsum()</code></li>
<li><code>describe()</code></li>
</ul>
<p>기본적으로 열 단위로 작동, 결측치는 행 또는 열의 모든 값이 결측치가 아니라면 기본적으로 무시함. </p>
<p><strong>행 단위로 작동하게 하려면 축을 <code>axis=1</code> 또는 <code>axis=&#39;columns&#39;</code>로 지정하고, 결측치를 무시하지 않으려면 <code>skipna=False</code>로 지정한다.</strong></p>
<pre><code class="language-python">df = pd.DataFrame([[1.4, np.nan], [7.1, -4.5],
                   [np.nan, np.nan], [0.75, -1.3]],
                  index=[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;],
                  columns=[&#39;one&#39;, &#39;two&#39;])
df</code></pre>
<pre><code>     one    two
a    1.40    NaN
b    7.10    -4.5
c    NaN      NaN
d    0.75    -1.3
#표 형태임.</code></pre><hr>
<p><strong><code>sum()</code> 메서드</strong></p>
<p> <strong>행/열 단위 합 계산</strong></p>
<pre><code class="language-python">df.sum()
# one 9.25
# two -5.80
# dtype: float64</code></pre>
<p>결측치를 무시하지 않으면, 결측치가 포함된 행/렬에 대한 계산은 하지 않음.</p>
<pre><code class="language-python">df.sum(skipna=False)
# one NaN
# two NaN
# dtype: float64</code></pre>
<pre><code class="language-python">df.sum(axis=&#39;columns&#39;)
# a 1.40
# b 2.60
# c 0.00
# d -0/55
#dtype: float64</code></pre>
<p>시리즈는 하나의 열을 갖는 데이터프레임처럼 작동함.</p>
<pre><code class="language-python">df[&#39;one&#39;]
# a 1.40
# b 7.10
# c NaN
# d 0.75
# Name: one, dtype: float64</code></pre>
<pre><code class="language-python">df[&#39;one&#39;].sum()
#9.25</code></pre>
<hr>
<p><strong><code>mean()</code> 메서드</strong></p>
<p> <strong>평균값 계산</strong></p>
<pre><code class="language-python">df.mean()
# one 3.083333
# two -2.90000
# dtype: float64</code></pre>
<pre><code class="language-python">df.mear(axis=&#39;columns&#39;)
#a    1.400
#b    1.300
#c    NaN
#d   -0.275
#dtype: float64</code></pre>
<p>결측치를 무시하지 않으면, 결측치가 포함된 행/렬에 대한 계산은 하지 않음.</p>
<pre><code class="language-python">df.mean(skipna=False)
#one   NaN
#two   NaN
#dtype: float64</code></pre>
<pre><code class="language-python">df.mean(axis=&#39;columns&#39;, skipna=False)
#a      NaN
#b    1.300
#c      NaN
#d   -0.275
#dtype: float64</code></pre>
<p>시리즈의 경우도 동일하게 작동함.</p>
<pre><code class="language-python">df[&#39;one&#39;].mean()
#3.0833333333333335</code></pre>
<pre><code class="language-python">df[&#39;one&#39;].mean(skipna=False)
#NaN</code></pre>
<hr>
<p><strong><code>std()</code> 메서드</strong></p>
<p> <strong>표준편차 계산</strong></p>
<pre><code class="language-python">df.std()
#one    3.493685
#two    2.262742
#dtype: float64</code></pre>
<pre><code class="language-python">df.std(axis=&#39;columns&#39;,skipna=False)
#a    NaN
#b    8.202439
#c    NaN
#d    1.449569
#dtype: float64</code></pre>
<hr>
<p><strong><code>idxmax()</code>/<code>idxmin()</code></strong></p>
<p> <strong>최댓값/최솟값을 갖는 인덱스 확인</strong></p>
<p>아래 코드는 열별 최댓값을 갖는 인덱스를 찾아줌.</p>
<pre><code class="language-python">df.imax()
#one b
#two b
#dtype: object</code></pre>
<hr>
<p><strong><code>cumsum()</code></strong></p>
<p> <strong>누적 합 계산</strong></p>
<pre><code class="language-python">df.cumsum()</code></pre>
<pre><code>     one     two
a     1.40     NaN
b     8.50     -4.5
c     NaN     NaN
d     9.25     -5.8
#표 형태임</code></pre><hr>
<p><strong><code>describe()</code></strong></p>
<p> <strong>요약 통계 보여주기</strong></p>
<p>수치형 데이터의 경우 평균값, 표준편차, 사분위수 등의 통계 정보를 요약해서 보여줌.</p>
<pre><code class="language-python">df.describe()</code></pre>
<pre><code>         one         two
count    3.000000      2.000000
mean    3.083333    -2.900000
std      3.493685     2.262742
min      0.750000    -4.500000
25%      1.075000    -3.700000
50%     1.400000    -2.900000
75%      4.250000    -2.100000
max     7.100000    -1.300000
#표 형태임
</code></pre><hr>
<h3 id="상관관계와-공분산"><strong>상관관계와 공분산</strong></h3>
<p>금융 사이트에서 구한 4 개 회사의 주가(price)와 거래량(volume)을 담고 있는 두 개의 데이터를 이용하여 상관계수와 공분산을 계산할 것임. </p>
<p>이를 위해 먼저 바이너리 파일 두 개를 다운로드해서 지정된 하위 디렉토리에 저장해야 함.</p>
<ul>
<li>파일 저장 디렉토리 지정 및 생성</li>
</ul>
<pre><code class="language-python">from pathlib import Path

data_path = Path() / &quot;examples&quot;

data_path.mkdir(parents=True, exist_ok=True)</code></pre>
<ul>
<li>특정 서버에서 파일 다운로드 함수</li>
</ul>
<pre><code class="language-python">import requests

# 파일 서버 기본 주소
base_url = &quot;https://raw.githubusercontent.com/codingalzi/datapy/master/jupyter-book/examples/&quot;

def myWget(filename):
    # 다운로드 대상 파일 경로
    file_url = base_url + filename

    # 저장 경로와 파일명
    target_path = data_path / filename

    data = requests.get(file_url)

    with open(target_path, &#39;wb&#39;) as f:
        f.write(data.content)</code></pre>
<p>두 개의 픽클 파일 다운로드.</p>
<ul>
<li><strong>pkl 파일:</strong> 판다스에서 제공하는 객체를 <strong><code>to_pickle()</code> 메서드</strong>를 이용하여 컴퓨터에 파일로 저장할 때 사용되는 바이너리 파일.</li>
</ul>
<pre><code class="language-python">myWget(&quot;yahoo_price.pkl&quot;)
myWget(&quot;yahoo_volume.pkl&quot;)</code></pre>
<p>다운로드한 두 개의 데이터를 불러옴.</p>
<ul>
<li><strong><code>read_pickle()</code>:</strong> 저장된 pkl 파일을 파이썬으로 불러오는 함수</li>
</ul>
<p>아래 코드는 일별 주가 데이터를 불러온다. 2010년 1월 4일부터 2016년 10월 21일까지의 데이터 1714개를 담고 있음.</p>
<pre><code class="language-python">price=pd.read_pickle(&#39;examples/yahoo_price.pkl&#39;)
price</code></pre>
<p>아래 코드는 동일 회사, 동일 날짜의 1일 거래량(volume) 담고 있는 데이터를 불러옴.</p>
<pre><code class="language-python">volume = pd.read_pickle(&#39;examples/yahoo_volume.pkl&#39;)
volume</code></pre>
<p>주가의 일단위 변화율을 알아보기 위해 퍼센트 변화율을 확인함.</p>
<p><strong>참고:</strong> 증권분야에서 return은 이익율을 의미함.</p>
<pre><code class="language-python">returns = price.pct_change()
returns.tail()</code></pre>
<hr>
<p><strong><code>corr()</code>/<code>cov()</code> 메서드</strong></p>
<p>상관계수와 공분산 모두 두 확률변수 사이의 선형관계를 보여줌</p>
<p><strong>상관계수와 공분산의 차이점</strong></p>
<p>| <strong>공분산</strong> | 두 확률변수 X, Y 사이의 선형관계를 계량화함.
양/음수 여부에 따른 선형관계를 보이며, 절댓값이 클수록 선형관계가 강함.
but 사용되는 확률변수의 척도(scale)에 많은 영향을 받음.
#정규화한 값인 상관계수를 사용하는 이유 | Cov(X,Y)=E((X−μX)(Y−μY))
μX=E(X)=∑X/n
μY=E(Y)=∑Y/n
 |
| --- | --- | --- |
| <strong>상관계수</strong> | 두 확률변수 사이의 선형관계를 -1과 1 사이의 값으로 표현함.
양/음수 여부에 따른 선형관계로 절댓값이 1에 가까울수록 선형관계가 강함. | ρ=Cov(X,Y)/σX⋅σY
σX=√Var(X)
Var(X)=∑(X−μX)^2/n
Var(Y)=∑(X−μY)^2/n |</p>
<p>&#39;MSFT&#39;와 &#39;IBM&#39; 사이의 공분산은 다음과 같음.</p>
<pre><code class="language-python">returns[&#39;MSFT&#39;].cov(returns[&#39;IBM&#39;])
#8.870655479703546e-05</code></pre>
<p>&#39;MSFT&#39;와 &#39;IBM&#39; 사이의 상관계수는 다음과 같음.</p>
<pre><code class="language-python">returns[&#39;MSFT&#39;].corr(returns[&#39;IBM&#39;])
#0.49976361144151144</code></pre>
<p>전체 회사를 대상으로 하는 상관계수와 공분산을 계산할 수도 있음.</p>
<pre><code class="language-python">returns.cov()
returns.corr()</code></pre>
<hr>
<h3 id="중복과-빈도"><strong>중복과 빈도</strong></h3>
<p><strong><code>unique()</code> 메서드</strong></p>
<p>시리즈에서 사용된 값을 중복 없이 확인</p>
<p> <code>set()</code> 함수와 유사하게 작동하며, 넘파이 어레이를 반환.</p>
<pre><code class="language-python">obj = pd.Series([&#39;c&#39;, &#39;a&#39;, &#39;d&#39;, &#39;a&#39;, &#39;a&#39;, &#39;b&#39;, &#39;b&#39;, &#39;c&#39;, &#39;c&#39;])
obj</code></pre>
<pre><code>0    c
1    a
2    d
3    a
4    a
5    b
6    b
7    c
8    c
dtype: object</code></pre><pre><code class="language-python">uniques = obj.unique()
uniques</code></pre>
<pre><code>array([&#39;c&#39;, &#39;a&#39;, &#39;d&#39;, &#39;b&#39;], dtype=object)
</code></pre><hr>
<p><strong><code>value_counts()</code> 메서드</strong></p>
<p>값들의 빈도수를 확인</p>
<pre><code class="language-python">obj.value_counts()</code></pre>
<pre><code>c    3
a    3
b    2
d    1
Name: count, dtype: int64</code></pre>]]></description>
        </item>
        <item>
            <title><![CDATA[Pandas3_1]]></title>
            <link>https://velog.io/@data_lover/Pandas31</link>
            <guid>https://velog.io/@data_lover/Pandas31</guid>
            <pubDate>Wed, 12 Mar 2025 07:25:21 GMT</pubDate>
            <description><![CDATA[<h1 id="데이터프레임-중심-프로그래밍">데이터프레임 중심 프로그래밍</h1>
<h2 id="1-기본-설정">1. 기본 설정</h2>
<h3 id="1-1-시리즈series">1-1. 시리즈(Series)</h3>
<ul>
<li>1차원 데이터 구조로, 인덱스와 값(value)으로 구성됨.</li>
<li>리스트, 딕셔너리, 넘파이 배열 등을 활용하여 생성 가능.</li>
</ul>
<h3 id="1-2-데이터프레임dataframe">1-2. 데이터프레임(DataFrame)</h3>
<ul>
<li>2차원 데이터 구조로, 여러 개의 시리즈가 모여 만들어짐.</li>
<li>행(row)과 열(column)로 구성됨.</li>
<li>딕셔너리, 리스트, 넘파이 배열 등을 활용하여 생성 가능.</li>
</ul>
<hr>
<h2 id="2-시리즈-산술연산">2. 시리즈 산술연산</h2>
<ul>
<li>시리즈 간의 산술연산은 같은 인덱스를 기준으로 수행됨.</li>
<li>연산 대상이 없는 인덱스 값은 NaN(결측치)로 처리됨.</li>
</ul>
<h3 id="예제-덧셈">예제 (덧셈)</h3>
<pre><code class="language-python">import pandas as pd

s1 = pd.Series([10, 20, 30], index=[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;])
s2 = pd.Series([5, 15, 25], index=[&#39;b&#39;, &#39;c&#39;, &#39;d&#39;])

result = s1 + s2
print(result)
</code></pre>
<pre><code>a     NaN
b    25.0
c    45.0
d     NaN
dtype: float64
</code></pre><h3 id="예제-뺄셈">예제 (뺄셈)</h3>
<pre><code class="language-python">result = s1 - s2
print(result)
</code></pre>
<pre><code>a    NaN
b     5.0
c     5.0
d    NaN
dtype: float64
</code></pre><h3 id="예제-곱셈">예제 (곱셈)</h3>
<pre><code class="language-python">result = s1 * s2
print(result)
</code></pre>
<pre><code>a      NaN
b    300.0
c    750.0
d      NaN
dtype: float64
</code></pre><h3 id="예제-나눗셈">예제 (나눗셈)</h3>
<pre><code class="language-python">result = s1 / s2
print(result)
</code></pre>
<pre><code>a    NaN
b    1.333333
c    1.2
d    NaN
dtype: float64
</code></pre><ul>
<li>‘a’와 ‘d’는 대응되는 값이 없어 NaN(결측치)로 표시됨.</li>
</ul>
<hr>
<h2 id="3-데이터프레임-산술연산">3. 데이터프레임 산술연산</h2>
<ul>
<li>같은 열(column)과 같은 행(index)을 기준으로 연산이 수행됨.</li>
<li>대응되는 값이 없으면 NaN(결측치)로 처리됨.</li>
</ul>
<h3 id="예제-덧셈-1">예제 (덧셈)</h3>
<pre><code class="language-python">df1 = pd.DataFrame({&#39;A&#39;: [1, 2, 3], &#39;B&#39;: [4, 5, 6]})
df2 = pd.DataFrame({&#39;A&#39;: [10, 20, 30], &#39;C&#39;: [40, 50, 60]})

result = df1 + df2
print(result)
</code></pre>
<pre><code>      A   B   C
0  11.0 NaN NaN
1  22.0 NaN NaN
2  33.0 NaN NaN
</code></pre><h3 id="예제-뺄셈-1">예제 (뺄셈)</h3>
<pre><code class="language-python">result = df1 - df2
print(result)
</code></pre>
<pre><code>      A   B   C
0  -9.0 NaN NaN
1 -18.0 NaN NaN
2 -27.0 NaN NaN
</code></pre><h3 id="예제-곱셈-1">예제 (곱셈)</h3>
<pre><code class="language-python">result = df1 * df2
print(result)
</code></pre>
<pre><code>      A   B   C
0  10.0 NaN NaN
1  40.0 NaN NaN
2  90.0 NaN NaN
</code></pre><h3 id="예제-나눗셈-1">예제 (나눗셈)</h3>
<pre><code class="language-python">result = df1 / df2
print(result)
</code></pre>
<pre><code>      A   B   C
0  0.1 NaN NaN
1  0.1 NaN NaN
2  0.1 NaN NaN
</code></pre><ul>
<li>‘B’와 ‘C’ 열은 상대 데이터프레임에 없어서 NaN으로 표시됨.</li>
</ul>
<hr>
<h2 id="4-연산과-결측치">4. 연산과 결측치</h2>
<ul>
<li>연산 시 NaN(결측치)이 포함되면 결과값도 NaN이 됨.</li>
<li>결측치를 처리하기 위한 메소드 활용 가능.</li>
</ul>
<h3 id="자주-사용되는-연산-메소드">자주 사용되는 연산 메소드</h3>
<table>
<thead>
<tr>
<th>메소드</th>
<th>설명</th>
</tr>
</thead>
<tbody><tr>
<td>add()</td>
<td>덧셈(+) 수행</td>
</tr>
<tr>
<td>sub()</td>
<td>뺄셈(-) 수행</td>
</tr>
<tr>
<td>mul()</td>
<td>곱셈(*) 수행</td>
</tr>
<tr>
<td>div()</td>
<td>나눗셈(/) 수행</td>
</tr>
<tr>
<td>fillna()</td>
<td>NaN 값을 특정 값으로 대체</td>
</tr>
<tr>
<td>dropna()</td>
<td>NaN 값을 포함한 행/열 제거</td>
</tr>
</tbody></table>
<h3 id="예제-fillna-활용">예제 (fillna 활용)</h3>
<pre><code class="language-python">result = df1.add(df2, fill_value=0)
print(result)
</code></pre>
<pre><code>      A    B     C
0  11.0  4.0  40.0
1  22.0  5.0  50.0
2  33.0  6.0  60.0
</code></pre><ul>
<li>NaN 대신 0을 채워 연산 수행.</li>
</ul>
<hr>
<h2 id="5-브로드캐스팅">5. 브로드캐스팅</h2>
<ul>
<li>차원이 다른 데이터 간 연산을 자동으로 확장하여 수행하는 기능.</li>
</ul>
<h3 id="5-1-차원-맞추기">5-1. 차원 맞추기</h3>
<ul>
<li>데이터프레임과 시리즈 간 연산 시 자동으로 차원이 맞춰짐.</li>
</ul>
<h3 id="5-2-데이터프레임과-시리즈-간-연산">5-2. 데이터프레임과 시리즈 간 연산</h3>
<pre><code class="language-python">df = pd.DataFrame({&#39;A&#39;: [1, 2, 3], &#39;B&#39;: [4, 5, 6]})
s = pd.Series([10, 20, 30])

result = df + s
print(result)
</code></pre>
<pre><code>    A   B
0  11  14
1  22  25
2  33  36
</code></pre><ul>
<li>시리즈의 값이 각 행(row)에 더해짐.</li>
</ul>
<h3 id="5-3-공통-인덱스-존재-시">5-3. 공통 인덱스 존재 시</h3>
<pre><code class="language-python">s = pd.Series([10, 20], index=[&#39;A&#39;, &#39;B&#39;])
result = df + s
print(result)
</code></pre>
<pre><code>     A   B
0  11  24
1  12  25
2  13  26
</code></pre><ul>
<li>공통 인덱스만 연산에 적용됨.</li>
</ul>
<h3 id="5-4-axis0-또는-axisindex-적용">5-4. axis=0 또는 axis=&#39;index&#39; 적용</h3>
<pre><code class="language-python">result = df.add(s, axis=0)
print(result)
</code></pre>
<pre><code>     A   B
0  11  24
1  12  25
2  13  26
</code></pre><ul>
<li>axis=0을 지정하면 행(row) 방향으로 브로드캐스팅이 적용됨.</li>
</ul>
]]></description>
        </item>
    </channel>
</rss>