0Pricing
Pandas & NumPy Academy · 강의

DataFrames 만들기

리스트의 dict, dict의 리스트, NumPy 배열로 DataFrames를 구성한 다음 shape, columns, dtypes를 확인합니다.

DataFrames 만들기은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Pandas & NumPy Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What Is a DataFrame?

A DataFrame is a two-dimensional, size-mutable, labelled data structure — essentially a table with rows and columns, similar to a spreadsheet or SQL table. Each column is a Pandas Series sharing the same row index. DataFrames can hold columns of different dtypes, making them perfect for real-world datasets that mix numbers, text, and dates.

import pandas as pd

df = pd.DataFrame({'name': ['Alice', 'Bob', 'Carol'],
                   'age': [30, 25, 35],
                   'score': [88.5, 72.0, 95.3]})
print(df)

Creating from a Dict of Lists

The most common way to construct a DataFrame is from a dict of lists: the keys become column names and the lists become column values. All lists must be the same length. The row index defaults to 0, 1, 2, ... unless you specify one with index=. This pattern mirrors how CSV data is often represented in Python.

import pandas as pd

df = pd.DataFrame({
    'city': ['Berlin', 'Paris', 'Rome'],
    'pop': [3.6, 2.2, 2.8],
    'country': ['DE', 'FR', 'IT']
})
print(df.shape)    # (3, 3)
print(df.dtypes)

Creating from a List of Dicts

You can also pass a list of dicts, where each dict represents one row. Missing keys in any dict produce NaN for that column. This format is common when consuming JSON APIs that return a list of record objects. Pandas aligns all keys across dicts to form the column set automatically.

import pandas as pd

rows = [
    {'name': 'Alice', 'age': 30, 'dept': 'Eng'},
    {'name': 'Bob',   'age': 25},              # 'dept' missing -> NaN
    {'name': 'Carol', 'age': 35, 'dept': 'HR'}
]
df = pd.DataFrame(rows)
print(df)

Creating from a NumPy Array

Passing a 2-D NumPy array creates a DataFrame with integer column names (0, 1, 2, ...) and a RangeIndex by default. Supply columns= and index= to add meaningful labels. This is the bridge between NumPy numerical computation and Pandas labelled data analysis.

import pandas as pd
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df = pd.DataFrame(arr,
                  columns=['x', 'y', 'z'],
                  index=['r1', 'r2', 'r3'])
print(df)

Setting a Custom Index at Creation

The index= parameter sets the row labels at creation time. Common choices include date strings, IDs, or category names that make row lookups meaningful. A well-chosen index makes .loc access intuitive and enables powerful time-series operations when the index is a DatetimeIndex.

import pandas as pd

df = pd.DataFrame(
    {'revenue': [100, 200, 150], 'costs': [80, 160, 90]},
    index=['Jan', 'Feb', 'Mar']
)
print(df)
print(df.loc['Feb'])  # select row 'Feb'

Inspecting columns, dtypes, and index

Three attributes immediately tell you the structure of a DataFrame: df.columns gives an Index of column names, df.dtypes returns a Series mapping each column to its dtype, and df.index describes the row labels. These are the first checks to run on any new DataFrame to understand what data you have before transforming it.

import pandas as pd

df = pd.DataFrame({'a': [1, 2], 'b': [3.0, 4.0], 'c': ['x', 'y']})
print(df.columns)  # Index(['a', 'b', 'c'], dtype='object')
print(df.dtypes)
# a      int64
# b    float64
# c     object
print(df.index)    # RangeIndex(start=0, stop=2, step=1)

Specifying Column Order

When constructing from a dict, column order follows dict insertion order (Python 3.7+). If you need a specific order, pass the columns= parameter with a list of column names. Any name not in the data will produce a NaN column; any name in the data but not in the list will be excluded. This lets you select and order columns at construction time.

import pandas as pd

data = {'c': [3, 6], 'a': [1, 4], 'b': [2, 5]}
df = pd.DataFrame(data, columns=['a', 'b', 'c'])
print(df.columns.tolist())  # ['a', 'b', 'c']

Creating from a Dict of Series

Passing a dict of Pandas Series aligns on the union of all indices. Where a Series is missing a label that another has, the result cell is NaN. This is the most index-aware construction method and is used when combining separately computed columns that may have different row counts or labels.

import pandas as pd

s1 = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
s2 = pd.Series([10, 20], index=['b', 'c'])
df = pd.DataFrame({'col1': s1, 'col2': s2})
print(df)
#    col1  col2
# a   1.0   NaN
# b   2.0  10.0
# c   3.0  20.0

shape, len, and size

df.shape returns a tuple (nrows, ncols). len(df) returns the number of rows. df.size returns the total number of cells (rows × columns). These are the quickest sanity checks after loading data to confirm you received the expected number of records and that no columns were silently dropped.

import pandas as pd

df = pd.DataFrame({'a': range(5), 'b': range(5), 'c': range(5)})
print(df.shape)  # (5, 3)
print(len(df))   # 5
print(df.size)   # 15  (5 rows x 3 cols)

Creating an Empty DataFrame

You can create an empty DataFrame with specific column names and dtypes for use as a template or accumulator. Append rows with pd.concat([df, new_row])m. Specifying dtypes at creation avoids expensive type inference when rows are added later. An empty DataFrame is also useful as a seed in iterative data collection loops.

import pandas as pd

df = pd.DataFrame(columns=['name', 'score'])
new_row = pd.DataFrame([{'name': 'Alice', 'score': 90}])
df = pd.concat([df, new_row], ignore_index=True)
print(df)

Copying a DataFrame

Assigning a DataFrame to a new variable creates a reference, not a copy — modifying one modifies the other. Use df.copy() to create an independent copy. This is important before making transformations you do not want to apply to the original, or when you want to keep a pre-cleaning backup while building a cleaned version.

import pandas as pd

original = pd.DataFrame({'a': [1, 2, 3]})
ref = original          # same object!
copy = original.copy()  # independent copy

ref['a'] = 99
print(original['a'].tolist())  # [99 99 99] -- ref modified original
print(copy['a'].tolist())      # [1, 2, 3]  -- copy unchanged

Quick Check

Test your understanding of creating DataFrames from this lesson.

Lesson Recap

In this lesson you learned: DataFrames can be created from dicts of lists, lists of dicts, or NumPy arrays, the columns, dtypes, and index attributes describe the table structure, and df.copy() is required to get an independent copy rather than a reference. Next up we select specific columns and rows using bracket notation, .loc, and .iloc.

자주 묻는 질문

“DataFrames 만들기” 강의는 무료인가요?

네 — “DataFrames 만들기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“DataFrames 만들기”에서 뭘 배우나요?

리스트의 dict, dict의 리스트, NumPy 배열로 DataFrames를 구성한 다음 shape, columns, dtypes를 확인합니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“DataFrames 만들기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. DataFrames 만들기
  2. 열과 행 선택
  3. 열 추가와 삭제
  4. 기본 DataFrame 검사
← Pandas & NumPy Academy(으)로 돌아가기