add colname to a dataframe in python

To add column names to a dataframe in python using Pandas library, you can use the columns attribute of a dataframe object. Below is an example:

main.py
import pandas as pd
import numpy as np

# create a dataframe with three columns
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df = pd.DataFrame(data)

# assign column names to dataframe
df.columns = ['col1', 'col2', 'col3']

print(df)
240 chars
12 lines

This will output the following dataframe with column names col1, col2, and col3:

main.py
   col1  col2  col3
0     1     2     3
1     4     5     6
2     7     8     9
80 chars
5 lines

In this example, we first created a 3x3 numpy array and then converted it to a Pandas dataframe. We then assigned the column names to the dataframe using the columns attribute.

gistlibby LogSnag