日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

pandas刪除某行或某列數(shù)據(jù)的實(shí)現(xiàn)示例_python

作者:一位代碼 ? 更新時(shí)間: 2022-09-24 編程語言

首先,創(chuàng)建一個(gè)DataFrame格式數(shù)據(jù)作為舉例數(shù)據(jù)。

# 創(chuàng)建一個(gè)DataFrame格式數(shù)據(jù)
data = {'a': ['a0', 'a1', 'a2'],
        'b': ['b0', 'b1', 'b2'],
        'c': [i for i in range(3)],
        'd': 4}
df = pd.DataFrame(data)
print('舉例數(shù)據(jù)情況:\n', df)

在這里插入圖片描述

注:DataFrame是最常用的pandas對象,使用pandas讀取數(shù)據(jù)文件后,數(shù)據(jù)就以DataFrame數(shù)據(jù)結(jié)構(gòu)存儲在內(nèi)存中。

pandas數(shù)據(jù)行列刪除,主要用到drop()和del函數(shù),用法如下:

1、drop()函數(shù)

語法:

DataFrame.drop(labels,axis=0,level=None,inplace=False,errors='raise')
參數(shù) 說明
labels 接收string或array,代表要刪除的行或列的標(biāo)簽(行名或列名)。無默認(rèn)值
axis 接收0或1,代表操作的軸(行或列)。默認(rèn)為0,代表行;1為列。
level 接收int或索引名,代表標(biāo)簽所在級別。默認(rèn)為None
inplace 接收布爾值,代表操作是否對原數(shù)據(jù)生效,默認(rèn)為False
errors errors='raise’會讓程序在labels接收到?jīng)]有的行名或者列名時(shí)拋出錯(cuò)誤導(dǎo)致程序停止運(yùn)行,errors='ignore’會忽略沒有的行名或者列名,只對存在的行名或者列名進(jìn)行操作。默認(rèn)為‘errors=‘raise’’。

實(shí)例1:刪除d列

df1 = df.drop(labels='d', axis=1)
print('刪除d列前:\n', df)
print('刪除d列后:\n', df1)

在這里插入圖片描述

實(shí)例2:刪除第一行

df2 = df.drop(labels=0)
print('刪除前:\n', df)
print('刪除列:\n', df2)

在這里插入圖片描述

實(shí)例3:同時(shí)刪除多行多列

df3 = df.drop(labels=['a', 'b'], axis=1) # 同時(shí)刪除a,b列
df4 = df.drop(labels=range(2)) # 等價(jià)于df.drop(labels=[0,1])
print('刪除前:\n', df)
print('刪除多列(a,b):\n', df3)
print('刪除多行(第1,2行):\n', df4)

在這里插入圖片描述

注意:(1)、刪除列的操作時(shí),axis參數(shù)不可省,因?yàn)閍xis默認(rèn)為0(行);
(2)、沒有加入inplace參數(shù),默認(rèn)不會對原來數(shù)據(jù)進(jìn)行修改,需要將結(jié)果賦值給新的變量。

2、del函數(shù)

語法:del df[‘列名’]
此操作會對原數(shù)據(jù)df進(jìn)行刪除,且一次只能刪除一列。
正確用法:

del df['d']
print('原地刪除d列后:\n', df)

在這里插入圖片描述

錯(cuò)誤用法:

del df[['a', 'b']]
print(df)

在這里插入圖片描述

原文鏈接:https://blog.csdn.net/LHJCSDNYL/article/details/124784943

欄目分類
最近更新