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
CodePudding user response:
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