1 根据索引删除列

df = pd.DataFrame(np.arange(12).reshape(3, 4), 
				columns=['A', 'B', 'C', 'D'])

# 根据列标签删除列
df.drop(['B', 'C'], axis=1) 
df.drop(columns=['B', 'C'])

# 根据索引删除行 
df.drop([0, 1])

2 根据索引或者行号删除行

import pandas as pd

df = pd.read_csv('./data/12/sample_pandas_normal.csv', index_col=0)
print(df)
#          age state  point
# name
# Alice     24    NY     64
# Bob       42    CA     92
# Charlie   18    CA     70
# Dave      68    TX     70
# Ellen     24    CA     88
# Frank     30    NY     57
print(df.drop('Charlie', axis=0))
#        age state  point
# name                   
# Alice   24    NY     64
# Bob     42    CA     92
# Dave    68    TX     70
# Ellen   24    CA     88
# Frank   30    NY     57
print(df.drop(['Bob', 'Dave', 'Frank']))
#          age state  point
# name                     
# Alice     24    NY     64
# Charlie   18    CA     70
# Ellen     24    CA     88

print(df.drop(index=['Bob', 'Dave', 'Frank']))
#          age state  point
# name                     
# Alice     24    NY     64
# Charlie   18    CA     70
# Ellen     24    CA     88
print(df.drop(df.index[[1, 3, 5]]))
#          age state  point
# name                     
# Alice     24    NY     64
# Charlie   18    CA     70
# Ellen     24    CA     88

print(df.drop(index=df.index[[1, 3, 5]]))
#          age state  point
# name                     
# Alice     24    NY     64
# Charlie   18    CA     70
# Ellen     24    CA     88


3 参考文献

[1]Pandas DataFrame 删除指定列
[2]12_Pandas.DataFrame删除指定行和列(drop)

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐