从 DataFrame 删除列
有时 DataFrame 中会包含您不再需要的列。为了简化数据,通常需要删除一些列。您还记得视频里提到,用哪个方法可以删除行或列吗?
假设您希望向公司相关方展示 PCE 的计算结果,但不想展示用于计算的中间列。请从给定的 DataFrame pce 中删除列 PCDG、PCND 和 PCESV,只保留 PCE 列。已为您提供列表 columns_to_drop。
本练习是课程的一部分
Python 金融进阶
练习说明
- 打印
pceDataFrame 的列名。 - 基于
pce创建一个新的 DataFrame,并去除列表columns_to_drop中的列。 - 打印新 DataFrame 的列名。
- 就地从 DataFrame
pce中删除columns_to_drop指定的列。
交互式实操练习
通过完成这段示例代码来试试这个练习。
columns_to_drop = ['PCDG', 'PCND', 'PCESV']
# Print the current columns of the DataFrame pce
____(pce.columns)
# Create new_pce by dropping columns_to_drop from pce
new_pce = pce.drop(columns=____)
# Print the columns of the new DataFrame
print(new_pce.____)
# Drop the columns in_place in the original DataFrame
pce.____(columns=columns_to_drop, inplace=____)
# Print the columns of the DataFrame pce
print(pce.columns)