程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

pandas - delete a row or column of data

編輯:Python

First, create a DataFrame format data as example data.

# Create a DataFrame format datadata = {'a': ['a0', 'a1', 'a2'],'b': ['b0', 'b1', 'b2'],'c': [i for i in range(3)],'d': 4}df = pd.DataFrame(data)print('Example data:\n', df)


Note: DataFrame is the most commonly used pandas object, use pandas to read data filesAfter that, the data is stored in memory as a DataFrame data structure.

Pandas data row and column deletion, mainly use drop() and del functions, usage is as follows:
1, drop() function
Syntax:
DataFrame.drop(labels,axis=0,level=None,inplace=False,errors='raise')

parametersDescriptionlabels accepts a string or array representing the label (row or column name) of the row or column to delete.No default valueaxis accepts 0 or 1, representing the axis (row or column) of the operation.The default is 0, which means row; 1 is column.level accepts an int or index name representing the level of the tag.Default is NoneinplaceReceive a boolean value, indicating whether the operation takes effect on the original data, the default is Falseerrorserrors='raise' will cause the program to throw an error when the labels receive the missing row name or column name, causing the program to stop running, errors='ignore' will ignore the missing row name or column name, only for existingRow name or column name to operate.Defaults to 'errors='raise''.

Example 1: delete column d

df1 = df.drop(labels='d', axis=1)print('Before deleting column d:\n', df)print('After deleting column d:\n', df1)


Example 2: delete the first line

df2 = df.drop(labels=0)print('Before delete:\n', df)print('Delete column:\n', df2)
​​​​​​​


Example 3: Delete multiple rows and multiple columns at the same time

p>
df3 = df.drop(labels=['a', 'b'], axis=1) # Delete columns a and b at the same timedf4 = df.drop(labels=range(2)) # Equivalent to df.drop(labels=[0,1])print('Before delete:\n', df)print('Delete multiple columns (a,b):\n', df3)print('Delete multiple lines (line 1, 2):\n', df4)


Note: (1) When deleting a column, the axis parameter cannot be omitted, because the axis defaults to 0 (row);
(2), without adding the inplace parameter, the original data will not be modified by default, and the result needs to be assigned to a new variable.

2. del function
Syntax: del df['column name']
This operation will delete the original data df, and only one column can be deleted at a time.
Correct usage:

del df['d']print('After deleting column d in place:\n', df)


Incorrect usage:

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


The above is the usage of pandas to delete a row and a column of data, drop() is more flexible and practical than del().


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved