Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert array into DataFrame in Python

import pandas as pd    
import numpy as np   
e = np.random.normal(size=100)  
e_dataframe = pd.DataFrame(e)     

When I input the code above, I get this answer:

enter image description here

But how do I change the column name?

like image 244
feng_h Avatar asked Jul 23 '17 10:07

feng_h


People also ask

How can you convert a NumPy array into a pandas DataFrame?

To convert a numpy array to pandas dataframe, we use pandas. DataFrame() function of Python Pandas library.

Can we create DataFrame from array?

Since a DataFrame is similar to a 2D Numpy array, we can create one from a Numpy ndarray . You should remember that the input Numpy array must be 2D, otherwise you will get a ValueError. If you pass a raw Numpy ndarray , the index and column names start at 0 by default.


2 Answers

You can add parameter columns or use dict with key which is converted to column name:

np.random.seed(123)
e = np.random.normal(size=10)  
dataframe=pd.DataFrame(e, columns=['a']) 
print (dataframe)
          a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740

e_dataframe=pd.DataFrame({'a':e}) 
print (e_dataframe)
          a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740
like image 51
jezrael Avatar answered Oct 21 '22 08:10

jezrael


In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column

import pandas as pd    
import numpy as np   
e = np.random.normal(size=100)  
e_dataframe = pd.DataFrame(e)      

e_dataframe.rename(index=str, columns={0:'new_column_name'})
like image 44
Christopher Matthews Avatar answered Oct 21 '22 08:10

Christopher Matthews