You can use one of the following three methods to add a header row to a pandas DataFrame:
#add header row when creating DataFrame df = pd.DataFrame(data=[data_values], columns=['col1', 'col2', 'col3']) #add header row after creating DataFrame df = pd.DataFrame(data=[data_values]) df.columns = ['A', 'B', 'C'] #add header row when importing CSV df = pd.read_csv('data.csv', names=['A', 'B', 'C'])
The following examples show how to use each of these methods in practice.
Example 1: Add Header Row When Creating DataFrame
The following code shows how to add a header row when creating a pandas DataFrame:
import pandas as pd import numpy as np #add header row when creating DataFrame df = pd.DataFrame(data=np.random.randint(0, 100, (10, 3)), columns =['A', 'B', 'C']) #view DataFrame df A B C 0 81 47 82 1 92 71 88 2 61 79 96 3 56 22 68 4 64 66 41 5 98 49 83 6 70 94 11 7 1 6 11 8 55 87 39 9 15 58 67
Example 2: Add Header Row After Creating DataFrame
The following code shows how to add a header row after creating a pandas DataFrame:
import pandas as pd import numpy as np #create DataFrame df = pd.DataFrame(data=np.random.randint(0, 100, (10, 3))) #add header row to DataFrame df.columns = ['A', 'B', 'C'] #view DataFrame df A B C 0 81 47 82 1 92 71 88 2 61 79 96 3 56 22 68 4 64 66 41 5 98 49 83 6 70 94 11 7 1 6 11 8 55 87 39 9 15 58 67
Example 3: Add Header Row When Importing DataFrame
The following code shows how to add a header row using the names argument when importing a pandas DataFrame from a CSV file:
import pandas as pd import numpy as np #import CSV file and specify header row names df = pd.read_csv('data.csv', names=['A', 'B', 'C']) #view DataFrame df A B C 0 81 47 82 1 92 71 88 2 61 79 96 3 56 22 68 4 64 66 41 5 98 49 83 6 70 94 11 7 1 6 11 8 55 87 39 9 15 58 67
Related: How to Read CSV Files with Pandas
Additional Resources
How to Add Rows to a Pandas DataFrame
How to Add a Numpy Array to a Pandas DataFrame
How to Count Number of Rows in Pandas DataFrame