添加与删除列
添加新的计算列,重命名现有列,并使用 drop() 删除不需要的列或行。
添加与删除列 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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.
常见问题解答
「添加与删除列」课时是免费的吗?
是的 — 「添加与删除列」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。
「添加与删除列」这节课中我会学到什么?
添加新的计算列,重命名现有列,并使用 drop() 删除不需要的列或行。 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Pandas & NumPy Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「添加与删除列」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?
能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。