Добавление и удаление столбцов
Добавляйте новые вычисляемые столбцы, переименовывайте существующие и удаляйте ненужные столбцы или строки с помощью drop()
«Добавление и удаление столбцов» — бесплатный урок Pandas & NumPy Academy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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) и разблокировать остальной курс Pandas & NumPy Academy, подпишись на CoddyKit PRO. Курс Pandas & NumPy Academy содержит 4 уроков всего.
Чему я научусь в уроке «Добавление и удаление столбцов»?
Добавляйте новые вычисляемые столбцы, переименовывайте существующие и удаляйте ненужные столбцы или строки с помощью drop() Ты практикуешь Pandas & NumPy Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Pandas & NumPy Academy?
Предыдущий опыт не требуется. Pandas & NumPy Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Добавление и удаление столбцов»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Pandas & NumPy Academy?
Да. Каждый урок Pandas & NumPy Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Создание DataFrames
- Выбор столбцов и строк
- Добавление и удаление столбцов
- Базовая проверка DataFrame