열 추가와 삭제
새로운 계산 열을 추가하고 기존 열의 이름을 바꾸며 drop()으로 원하지 않는 열이나 행을 삭제합니다.
열 추가와 삭제은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Pandas & NumPy Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Adding a New Column via Assignment
The simplest way to add a column is direct assignment: df['new_col'] = values. The right-hand side can be a scalar (broadcasts to all rows), a list of the same length, a NumPy array, a Pandas Series (aligned by index), or a computed expression involving existing columns. New columns are added to the right of the DataFrame.
import pandas as pd
df = pd.DataFrame({'price': [10.0, 20.0, 15.0], 'qty': [3, 5, 2]})
df['revenue'] = df['price'] * df['qty']
df['currency'] = 'USD'
print(df)Feature Engineering: Computed Columns
One of the most common DataFrame operations is creating derived features from existing columns. You can compute running totals, ratios, flags, or encode categorical values in a single vectorized expression. These computed columns update automatically when the source columns change if you recompute them, making feature engineering pipelines easy to reproduce.
import pandas as pd
df = pd.DataFrame({'salary': [50000, 80000, 60000],
'bonus': [5000, 12000, 7000]})
df['total_comp'] = df['salary'] + df['bonus']
df['bonus_pct'] = (df['bonus'] / df['salary'] * 100).round(1)
print(df)Using assign() for Method Chaining
df.assign(new_col=expression) returns a new DataFrame with the added column without modifying the original. Unlike direct assignment it fits naturally into a method chain. You can add multiple columns in one call, and later column expressions can reference earlier columns defined in the same assign() call using lambda functions.
import pandas as pd
df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
result = (df
.assign(sum_xy=lambda d: d['x'] + d['y'])
.assign(ratio=lambda d: d['x'] / d['sum_xy'])
)
print(result)Renaming Columns with rename()
df.rename(columns={'old': 'new'}) returns a new DataFrame with renamed columns. Pass a dict to rename selected columns without affecting others. You can also rename by function: df.rename(columns=str.upper) uppercases all column names. Always rename before merging DataFrames from different sources to ensure key columns align.
import pandas as pd
df = pd.DataFrame({'a': [1, 2], 'b': [3, 4], 'c': [5, 6]})
renamed = df.rename(columns={'a': 'alpha', 'b': 'beta'})
print(renamed.columns.tolist()) # ['alpha', 'beta', 'c']
# Rename all columns to uppercase
print(df.rename(columns=str.upper).columns.tolist()) # ['A', 'B', 'C']Cleaning Column Names
Real-world column names often have spaces, special characters, or inconsistent casing. A common preprocessing step is to normalise them: strip whitespace, convert to lowercase, and replace spaces with underscores. This makes columns accessible via dot notation and avoids quoting issues in SQL-like query strings.
import pandas as pd
df = pd.DataFrame(columns=['First Name', 'Last Name', 'Email Address'])
df.columns = (df.columns
.str.strip()
.str.lower()
.str.replace(' ', '_', regex=False)
)
print(df.columns.tolist()) # ['first_name', 'last_name', 'email_address']Inserting a Column at a Specific Position
df.insert(loc, column, value) inserts a column at integer position loc, shifting other columns to the right. This is useful when you want the new column to appear next to related columns rather than at the end. It modifies the DataFrame in place, unlike assign().
import pandas as pd
df = pd.DataFrame({'name': ['A', 'B'], 'score': [80, 90]})
df.insert(1, 'grade', ['B', 'A'])
print(df)
# name grade score
# 0 A B 80
# 1 B A 90Dropping Columns with drop()
df.drop(columns=['col1', 'col2']) returns a new DataFrame without those columns. The older syntax df.drop(['col1', 'col2'], axis=1) also works but is less readable. To drop in place, pass inplace=True. Always prefer returning a new DataFrame in pipelines to preserve the original for comparison or rollback.
import pandas as pd
df = pd.DataFrame({'a': [1,2], 'b': [3,4], 'c': [5,6], 'd': [7,8]})
cleaned = df.drop(columns=['b', 'd'])
print(cleaned.columns.tolist()) # ['a', 'c']Dropping Rows with drop()
df.drop(index=['r1', 'r2']) removes rows by label. df.drop([0, 2]) removes rows 0 and 2 from a default integer index. Dropping rows is commonly used to remove known bad records, outliers, or test rows after data cleaning. Prefer boolean indexing for condition-based removal to keep the code readable.
import pandas as pd
df = pd.DataFrame({'x': [10, 20, 30, 40]}, index=['a', 'b', 'c', 'd'])
trimmed = df.drop(index=['b', 'd'])
print(trimmed)
# x
# a 10
# c 30pop() to Remove and Return a Column
df.pop('col') removes the column from the DataFrame in place and returns it as a Series. This is useful when you need to extract a target column (label) from a feature matrix — you remove it from the DataFrame and hold it separately for use as the y variable in a model.
import pandas as pd
df = pd.DataFrame({'feature1': [1,2], 'feature2': [3,4], 'target': [0,1]})
y = df.pop('target') # removes column and returns as Series
X = df # remaining features
print(y.tolist()) # [0, 1]
print(X.columns.tolist()) # ['feature1', 'feature2']Reordering Columns
To reorder columns, select them in the desired order using df[['col3', 'col1', 'col2']]. For large DataFrames where you only want to move a few columns, compute the desired order programmatically: move priority columns to the front and let the rest follow. This is a common reporting step before exporting to Excel.
import pandas as pd
df = pd.DataFrame({'id': [1,2], 'score': [80,90], 'name': ['A','B']})
# Move 'name' and 'id' to front
cols = ['name', 'id'] + [c for c in df.columns if c not in ['name', 'id']]
df = df[cols]
print(df.columns.tolist()) # ['name', 'id', 'score']Updating Existing Column Values
Updating all values of an existing column uses the same assignment syntax as adding a new one: df['col'] = new_values. Use df.loc[mask, 'col'] = value to update only the rows matching a condition. Never use chained indexing for updates — always use .loc to avoid the SettingWithCopyWarning.
import pandas as pd
df = pd.DataFrame({'name': ['Alice', 'Bob', 'Carol'], 'score': [45, 80, 92]})
# Set scores below 50 to 50 (floor)
df.loc[df['score'] < 50, 'score'] = 50
print(df['score'].tolist()) # [50, 80, 92]Quick Check
Test your understanding of adding and dropping columns from this lesson.
Lesson Recap
In this lesson you learned: new columns are added via assignment or the method-chain-friendly assign(), rename() changes column names without altering data, and drop() removes columns or rows and returns a new DataFrame by default. Next up we use head(), tail(), info(), and describe() to quickly profile any DataFrame.
자주 묻는 질문
“열 추가와 삭제” 강의는 무료인가요?
네 — “열 추가와 삭제” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“열 추가와 삭제”에서 뭘 배우나요?
새로운 계산 열을 추가하고 기존 열의 이름을 바꾸며 drop()으로 원하지 않는 열이나 행을 삭제합니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“열 추가와 삭제” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.