6

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
1
  • 1
    How working df.columns = ["id","information"] ? Commented Sep 24, 2018 at 12:23

2 Answers 2

13

Try:

df = pd.DataFrame(
    np.row_stack([df.columns, df.values]),
    columns=['id', 'information']
)
Sign up to request clarification or add additional context in comments.

1 Comment

This line,adds a header to the existing data frame
9

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"]

3 Comments

but i'm not reading a csv, i'm using tabula to parse a pdf to dataframe, in that way, i will have a dataframe as output with out headers.
df.columns is not adding a header, it replacing the existing first row.
@SriramArvindLakshmanakumar - Yes, it was a bit unclear. But I have one idea - how is created original df from pdf ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.