如何在 pandas 中按索引删除列


您可以使用以下语法按索引号从 pandas DataFrame 中删除列:

 #drop first column from DataFrame
df. drop ( df.columns [0], axis= 1 , inplace= True )

您可以使用以下语法按索引号从 pandas DataFrame 中删除多列:

 #drop first, second, and fourth column from DataFrame
cols = [0, 1, 3]
df. drop (df. columns [cols], axis= 1 , inplace= True )

如果您的 DataFrame 具有重复的列名,您可以使用以下语法按索引号删除列:

 #define list of columns
cols = [x for x in range( df.shape [1])]

#drop second column
collars. remove (1)

#view resulting DataFrame
df. iloc [:, cols]

以下示例展示了如何在实践中按索引删除列。

示例1:通过索引删除列

以下代码显示了如何从 pandas DataFrame 中删除第一列:

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' team ': ['Mavs', 'Lakers', 'Spurs', 'Cavs'],
                   ' first ': ['Dirk', 'Kobe', 'Tim', 'Lebron'],
                   ' last ': ['Nowitzki', 'Bryant', 'Duncan', 'James'],
                   ' points ': [26, 31, 22, 29]})

#drop first column from DataFrame
df. drop ( df.columns [0], axis= 1 , inplace= True )

#view resulting dataFrame
df

        first last points
0 Dirk Nowitzki 26
1 Kobe Bryant 31
2 Tim Duncan 22
3 LeBron James 29

示例 2:按索引删除多列

以下代码显示了如何按索引删除 pandas DataFrame 中的多列:

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' team ': ['Mavs', 'Lakers', 'Spurs', 'Cavs'],
                   ' first ': ['Dirk', 'Kobe', 'Tim', 'Lebron'],
                   ' last ': ['Nowitzki', 'Bryant', 'Duncan', 'James'],
                   ' points ': [26, 31, 22, 29]})

#drop first, second and fourth columns from DataFrame
cols = [0, 1, 3] 
df. drop (df. columns [cols], axis= 1 , inplace= True )

#view resulting dataFrame
df

        last
0 Nowitzki
1 Bryant
2 Duncan
3 James

示例 3:通过索引删除具有重复项的列

以下代码显示了当存在重复的列名时如何通过 pandas DataFrame 中的索引号删除列:

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' team ': ['Mavs', 'Lakers', 'Spurs', 'Cavs'],
                   ' last ': ['Nowitzki', 'Bryant', 'Duncan', 'James'],
                   ' last ': ['Nowitzki', 'Bryant', 'Duncan', 'James'],
                   ' points ': [26, 31, 22, 29]},
                   columns=[' team ', ' last ', ' last ', ' points '])

#define list of columns range
cols = [x for x in range( df.shape [1])]

#remove second column in DataFrame
collars. remove (1)

#view resulting DataFrame
df. iloc [:, cols]

	team last points
0 Mavs Nowitzki 26
1 Lakers Bryant 31
2 Spurs Duncan 22
3 Cavs James 29

其他资源

如何在 Pandas 中合并两列
Pandas:如何按名称对列进行排序
Pandas:如何找到两列之间的差异
Pandas:如何根据条件添加列

添加评论

您的电子邮箱地址不会被公开。 必填项已用*标注