python学习之删除DataFrame某一行/列内容,,用法:DataFra
python学习之删除DataFrame某一行/列内容,,用法:DataFra
用法:DataFrame.drop(labels=None,axis=0, index=None, columns=None, inplace=False)
参数说明:
labels 就是要删除的行列的名字,用列表给定
axis 默认为0,指删除行,因此删除columns时要指定axis=1;
index 直接指定要删除的行
columns 直接指定要删除的列
inplace=False,默认该删除操作不改变原数据,而是返回一个执行删除操作后的新dataframe;
inplace=True,则会直接在原数据上进行删除操作,删除后无法返回。
因此,删除行列有两种方式:
1)labels=None,axis=0 的组合
2)index或columns直接指定要删除的行或列
>>>df = pd.DataFrame(np.arange(12).reshape(3,4), columns=[‘A‘, ‘B‘, ‘C‘, ‘D‘])>>>df A B C D0 0 1 2 31 4 5 6 72 8 9 10 11#Drop columns,两种方法等价>>>df.drop([‘B‘, ‘C‘], axis=1) A D0 0 31 4 72 8 11>>>df.drop(columns=[‘B‘, ‘C‘]) A D0 0 31 4 72 8 11# 第一种方法下删除column一定要指定axis=1,否则会报错>>> df.drop([‘B‘, ‘C‘])ValueError: labels [‘B‘ ‘C‘] not contained in axis#Drop rows>>>df.drop([0, 1]) A B C D2 8 9 10 11>>> df.drop(index=[0, 1]) A B C D 2 8 9 10 11删除指定的行呢
>>> import pandas as pd>>> df = {‘DataBase‘:[‘mysql‘,‘test‘,‘test‘,‘test‘,‘test‘],‘table‘:[‘user‘,‘student‘,‘course‘,‘sc‘,‘book‘]}>>> df = pd.DataFrame(df)>>> df DataBase table0 mysql user1 test student2 test course3 test sc4 test book#删除table值为sc的那一行>>> df.drop(index=(df.loc[(df[‘table‘]==‘sc‘)].index)) DataBase table0 mysql user1 test student2 test course4 test book
#多行也可以哦>>> df.drop(index=(df.loc[(df[‘DataBase‘]==‘test‘)].index)) DataBase table0 mysql user
python学习之删除DataFrame某一行/列内容
评论关闭