pandas 删除DataFrame中的列
示例
有两种方法可以删除DataFrame中的列。
import numpy as np
import pandas as pd
np.random.seed(0)
pd.DataFrame(np.random.randn(5, 6), columns=list('ABCDEF'))
print(df)
# Output:
# A B C D E F
# 0 -0.895467 0.386902 -0.510805 -1.180632 -0.028182 0.428332
# 1 0.066517 0.302472 -0.634322 -0.362741 -0.672460 -0.359553
# 2 -0.813146 -1.726283 0.177426 -0.401781 -1.630198 0.462782
# 3 -0.907298 0.051945 0.729091 0.128983 1.139401 -1.234826
# 4 0.402342 -0.684810 -0.870797 -0.578850 -0.311553 0.0561651)使用del
del df['C'] print(df) # Output: # A B D E F # 0 -0.895467 0.386902 -1.180632 -0.028182 0.428332 # 1 0.066517 0.302472 -0.362741 -0.672460 -0.359553 # 2 -0.813146 -1.726283 -0.401781 -1.630198 0.462782 # 3 -0.907298 0.051945 0.128983 1.139401 -1.234826 # 4 0.402342 -0.684810 -0.578850 -0.311553 0.056165
2)使用drop
df.drop(['B', 'E'], axis='columns', inplace=True) # or df = df.drop(['B', 'E'], axis=1) without the option inplace=True print(df) # Output: # A D F # 0 -0.895467 -1.180632 0.428332 # 1 0.066517 -0.362741 -0.359553 # 2 -0.813146 -0.401781 0.462782 # 3 -0.907298 0.128983 -1.234826 # 4 0.402342 -0.578850 0.056165
3)drop与列号一起使用
要使用列整数而不是名称(请记住列索引从零开始):
df.drop(df.columns[[0, 2]], axis='columns') print(df) # Output: # D # 0 -1.180632 # 1 -0.362741 # 2 -0.401781 # 3 0.128983 # 4 -0.578850
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下