利用numpy删除DataFrame某一行/列、多行内容
生活随笔
收集整理的這篇文章主要介紹了
利用numpy删除DataFrame某一行/列、多行内容
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、用法:
DataFrame.drop(labels=None,axis=0, index=None, columns=None, inplace=False)
參數(shù)說明:
labels:就是要?jiǎng)h除的行列的名字,用列表給定
axis: 默認(rèn)為0,指刪除行,因此刪除columns時(shí)要指定axis=1;
index:?直接指定要?jiǎng)h除的行
columns: 直接指定要?jiǎng)h除的列
inplace=False:默認(rèn)該刪除操作不改變原數(shù)據(jù),而是返回一個(gè)執(zhí)行刪除操作后的新dataframe;
inplace=True:則會直接在原數(shù)據(jù)上進(jìn)行刪除操作,刪除后無法返回。
?
二、刪除行列有兩種方式:
1)labels=None,axis=0 的組合
2)index或columns直接指定要?jiǎng)h除的行或列
?
示例:
>>>df = pd.DataFrame(np.arange(12).reshape(3,4), columns=['A', 'B', 'C', 'D'])>>>dfA B C D0 0 1 2 31 4 5 6 72 8 9 10 11#Drop columns,兩種方法等價(jià)>>>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,否則會報(bào)錯(cuò) >>> 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 D2 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) >>> dfDataBase table 0 mysql user 1 test student 2 test course 3 test sc 4 test book#刪除table值為sc的那一行 >>> df.drop(index=(df.loc[(df['table']=='sc')].index))DataBase table 0 mysql user 1 test student 2 test course 4 test book刪除多行:
>>> df.drop(index=(df.loc[(df['DataBase']=='test')].index))DataBase table 0 mysql user?
總結(jié)
以上是生活随笔為你收集整理的利用numpy删除DataFrame某一行/列、多行内容的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中的下标索引
- 下一篇: python写程序注意事项(很重要)