python Delete columns and columns of csv files
- 2021-10-25 07:08:08
- OfStack
Step 1 Read data
Use the read_csv () function in pandas to read out the data in the csv file:
import pandas as pd
df = pd.read_csv("comments.csv")
df.head(2)
Use drop function to delete rows or columns of data in files.
2. Delete Column Action
Method 1: Suppose the name of the column we want to delete is' Viewer ID ',' Score ':
df=df.drop([' Audience ID',' Score '],axis=1)
Method 2:
# Delete the specified column
df.drop(columns=[" City "])
You can delete the specified column
3. Delete row action
Delete certain lines
df.drop([1,2]) # Delete 1,2 The whole row of data for the row
Delete rows (a range)
# Delete rows (a range)
df.drop(df.index[3:6],inplace=True)
Re-save the data to the csv file
# If you want to save a new csv File, otherwise
df.to_csv("data_new.csv",index=False,encoding="utf-8")
4. Description of related parameters of drop function:
The parameter axis=0 indicates that the row is operated, and if the column is operated, the default parameter is changed to axis=1.
The parameter inplace=False means that the deletion operation does not change the original data and returns a new dataframe after the deletion operation. If the original data is directly deleted, the default parameter is changed to inplace=True.
5. Description of related parameters of to_csv function:
The parameter index = False indicates that the output does not display the index (index) value.
Parameter encoding= "utf-8" indicates that the saved file encoding format is utf-8.
The above is the operation of deleting rows or columns for CSV file data, and the same is true for deleting rows or columns for Excel file data.