Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas: How to change titles of columns

I am creating a numpy matrix (2 columns, each 10 elements).
After conversion to a Pandas Dataframe I want to change the names of the columns from 0->x and 1->y.
How is the solution for this?

import numpy as np
import pandas as pd

x = np.arange(10)
y = x**2

# create numpy matrix of (2 x 10) 
matrix = np.stack((x, y), axis=-1)

#conversion to Pandas
df = pd.DataFrame(matrix)

print(df)

    0   1
0   0   0
1   1   1
2   2   4
3   3   9
4   4   16
5   5   25
6   6   36
7   7   49
8   8   64
9   9   81

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Use columns parameter of DataFrame constructor:

df = pd.DataFrame(matrix, columns=['x', 'y'])
print(df)

# Output
   x   y
0  0   0
1  1   1
2  2   4
3  3   9
4  4  16
5  5  25
6  6  36
7  7  49
8  8  64
9  9  81
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading