首先,創建一個DataFrameFormat data as example data.
# 創建一個DataFrame格式數據
data = {
'a': ['a0', 'a1', 'a2'],
'b': ['b0', 'b1', 'b2'],
'c': [i for i in range(3)],
'd': 4}
df = pd.DataFrame(data)
print('Example data situation:\n', df)
注:DataFrame是最常用的pandas對象,使用pandasAfter reading the data file,數據就以DataFrame數據結構存儲在內存中.
pandasData row and column deletion,主要用到drop()和del函數,用法如下:
1、drop()函數
語法:
DataFrame.drop(labels,axis=0,level=None,inplace=False,errors=’raise’)
實例1:刪除d列
df1 = df.drop(labels='d', axis=1)
print('刪除d列前:\n', df)
print('刪除d列後:\n', df1)
實例2:刪除第一行
df2 = df.drop(labels=0)
print('刪除前:\n', df)
print('刪除列:\n', df2)
實例3:Delete multiple rows and multiple columns at the same time
df3 = df.drop(labels=['a', 'b'], axis=1) # 同時刪除a,b列
df4 = df.drop(labels=range(2)) # 等價於df.drop(labels=[0,1])
print('刪除前:\n', df)
print('刪除多列(a,b):\n', df3)
print('刪除多行(第1,2行):\n', df4)
注意:(1)、When deleting a column,axis參數不可省,因為axis默認為0(行);
(2)、沒有加入inplace參數,By default, the original data will not be modified,The result needs to be assigned to a new variable.
2、del函數
語法:del df[‘列名’]
This operation is performed on the original datadf進行刪除,And only one column can be deleted at a time.
正確用法:
del df['d']
print('原地刪除d列後:\n', df)
錯誤用法:
del df[['a', 'b']]
print(df)
以上就是pandasDelete the usage of a row and a column of data,drop()相對於del()來說,靈活性更高,更為實用.
—end—
【微信搜索【one-digit code】即可關注我】