Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you delete the header in a dataframe?

I want to delete the header from a dataframe that I have. I read in the data from a csv file then I transposed it, but it created a new header that is the name of the file and the row that the data is from in the file.

Here's an example for a dataframe df:

     a.csv.1   a.csv.2   a.csv.3   ...
  x        5         6         1   ...
  y        2         3         2   ...  

I want to delete the a.csv.n row, but when I try df <- df[-1,] it deletes row x and not the top.

like image 261
user2654764 Avatar asked Aug 11 '13 19:08

user2654764


People also ask

How do I remove a header from a data frame?

In order to export pandas DataFrame to CSV without index (no row indices) use param index=False and to ignore/remove header use header=False param on to_csv() method.

How do I remove the top row of a data frame?

Use iloc to drop first row of pandas dataframe. Use drop() to remove first row of pandas dataframe. Use tail() function to remove first row of pandas dataframe.

How do I change the header of a DataFrame in Python?

Way 1: Using rename() method Create a data frame with multiple columns. Create a dictionary and set key = old name, value= new name of columns header. Assign the dictionary in columns. Call the rename method and pass columns that contain dictionary and inplace=true as an argument.


2 Answers

You can use names(df) to change the names of header or col names. If newnames is a list of names as newname<-list("col1","col2","col3"), then names(df)<-newname will give you a data with col names as col1 col2 col3.

As @ Henrik said, the col names should be non-empty. Setting the names(df)<-NULLwill give NA in col names.

If your data is csv file and if you use header=TRUE to read the data in R then the data will have same colnames as csv file, but if you set the header=FALSE, R will assign the colnames as V1,V2,...and your colnames in the original csv file appear as a first row.

anydata.csv  
      a b c  d
    1 1 2 3 13
    2 2 3 1 21

read.csv("anydata.csv",header=TRUE)
      a b c  d
    1 1 2 3 13
    2 2 3 1 21

read.csv("anydata.csv",header=FALSE)

  V1 V2 V3 V4
1  a  b  c  d
2  1  2  3 13
3  2  3  1 21
like image 76
Metrics Avatar answered Sep 21 '22 02:09

Metrics


It comes with some years of delay but you can simply use a vector renaming de columns:

## if you want to delete all column names:
colnames(df)[] <- ""

## if you want to delete let's say column 1:
colnames(df)[1] <- ""

## if you want to delete 1 to 3 and 7:
colnames(df)[c(1:3,7)] <- ""




like image 38
Ale Rey Avatar answered Sep 19 '22 02:09

Ale Rey