Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename unnamed column pandas dataframe

Tags:

python

pandas

csv

My csv file has no column name for the first column, and I want to rename it. Usually, I would do data.rename(columns={'oldname':'newname'}, inplace=True), but there is no name in the csv file, just ''.

like image 699
user2491254 Avatar asked Sep 29 '14 11:09

user2491254


People also ask

How do I rename an unnamed zero column?

rename( columns={0 :'new column name'}, inplace=True ) . There is no need to use 'Unnamed: 0' , simply use the column number, which is 0 in this case and then supply the 'new column name' .

How do I rename blank columns in pandas?

In order to rename a single column name on pandas DataFrame, you can use column={} parameter with the dictionary mapping of the old name and a new name.

Can we rename column in pandas?

One way of renaming the columns in a Pandas Dataframe is by using the rename() function. This method is quite useful when we need to rename some selected columns because we need to specify information only for the columns which are to be renamed. Example 1: Rename a single column.


2 Answers

You can view the current dataframe using data.head()

if that returns 'Unnamed: 0' as the column title, you can rename it in the following way:

data.rename( columns={'Unnamed: 0':'new column name'}, inplace=True ) 
like image 132
Marco Avatar answered Sep 18 '22 13:09

Marco


When you load the csv, use the option 'index_col' like

pd.read_csv('test.csv', index_col=0) 

index_col : int or sequence or False, default None Column to use as the row labels of the DataFrame. If a sequence is given, a MultiIndex is used. If you have a malformed file with delimiters at the end of each line, you might consider index_col=False to force pandas to not use the first column as the index (row names)

http://pandas.pydata.org/pandas-docs/dev/generated/pandas.io.parsers.read_csv.html

like image 30
KyungHoon Kim Avatar answered Sep 19 '22 13:09

KyungHoon Kim