Delete Certain Rows but Keep Header when Loading CSV File in Python (Example Code)
In this tutorial, I’ll demonstrate how to remove certain rows when importing a CSV file in Python.
Setting up the Example
import pandas as pd # Import pandas library in Python |
import pandas as pd # Import pandas library in Python
my_df = pd.DataFrame({'A':range(100, 105), # Construct new pandas DataFrame 'B':[9, 3, 7, 1, 2], 'C':['a', 'f', 'c', 'f', 'f'], 'D':range(35, 30, - 1)}) print(my_df) # A B C D # 0 100 9 a 35 # 1 101 3 f 34 # 2 102 7 c 33 # 3 103 1 f 32 # 4 104 2 f 31 |
my_df = pd.DataFrame({'A':range(100, 105), # Construct new pandas DataFrame 'B':[9, 3, 7, 1, 2], 'C':['a', 'f', 'c', 'f', 'f'], 'D':range(35, 30, - 1)}) print(my_df) # A B C D # 0 100 9 a 35 # 1 101 3 f 34 # 2 102 7 c 33 # 3 103 1 f 32 # 4 104 2 f 31
my_df.to_csv('my_df.csv') # Write exemplifying DataFrame to folder |
my_df.to_csv('my_df.csv') # Write exemplifying DataFrame to folder
Example: Ignore Particular Rows when Reading a CSV File
my_df_new = pd.read_csv('my_df.csv', # Import pandas DataFrame from CSV skiprows = [1, 2, 4]) print(my_df_new) # Unnamed: 0 A B C D # 0 2 102 7 c 33 # 1 4 104 2 f 31 |
my_df_new = pd.read_csv('my_df.csv', # Import pandas DataFrame from CSV skiprows = [1, 2, 4]) print(my_df_new) # Unnamed: 0 A B C D # 0 2 102 7 c 33 # 1 4 104 2 f 31