Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Header to a DataFrame Pandas

i have a DataFrame:

Index   1   Dr. Santosh Kumar
0      NaN  BHR/ 6681/148/1/134094/2007-08/L
1      NaN  B/301, Laxmi Apartment
2      NaN  New Chitragupta Nagar, Kankerbagh
3      NaN  Patna – 800 020
4      NaN  NaN
5      2    Dr. Deepak Kumar
6      NaN  BHR/ 6682/148/2/134095/2007-08/L
7      NaN  At & P.o-  Bairia
8      NaN  P.s- Gourichak
9      NaN  Patna – 800 007

i want to add an header to this dataframe,

df = pd.DataFrame([df],columns = ["id","information"])

but i get this error:

ValueError: Shape of passed values is (1, 1), indices imply (2, 1)

so final output should be:

Index   id  information
0       1   Dr. Santosh Kumar
1       NaN BHR/ 6681/148/1/134094/2007-08/L
2       NaN B/301, Laxmi Apartment
3       NaN New Chitragupta Nagar, Kankerbagh
4       NaN Patna – 800 020
5       NaN NaN
6       2   Dr. Deepak Kumar
7       NaN BHR/ 6682/148/2/134095/2007-08/L
8       NaN At & P.o-  Bairia
9       NaN P.s- Gourichak
10      NaN Patna – 800 007
like image 859
Sriram Arvind Lakshmanakumar Avatar asked Sep 24 '18 12:09

Sriram Arvind Lakshmanakumar


2 Answers

Try:

df = pd.DataFrame(
    np.row_stack([df.columns, df.values]),
    columns=['id', 'information']
)
like image 200
piRSquared Avatar answered Oct 13 '22 10:10

piRSquared


You can add columns names by parameter names in read_csv if no header file:

df = pd.read_csv(file, names=["id","information"])

If want set columns names by list:

df.columns = ["id","information"]
like image 39
jezrael Avatar answered Oct 13 '22 11:10

jezrael