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')
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
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().