Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename Pandas dataframe with NaN header

i currently work with dataframes, and i'm stacking them thus to achieve specific format. I have a question i'm trying to change name of the header but it doesn't work ( by using.. .rename(columns={'NaN'='type', inplace=True), same thing im trying to change the name of columns '6' to Another with the same principe as mentioned.

Here:

                                               NaN Quantity
6                                                                 
01/06                       KULUTUS - CONSUMPTION  8976.27     
01/06  TEOLLISUUSKULUTUS - INDUSTRIAL CONSUMPTION  4121.36    
01/06             MUU KULUTUS - OTHER CONSUMPTION  4854.91
like image 400
BEAst Avatar asked Aug 07 '17 11:08

BEAst


3 Answers

I think you need rename by dict or Index.fillna:

df = df.rename(columns={np.nan: 'type'})

df.columns = df.columns.fillna('type')

Sample:

df = pd.DataFrame([[1,4]], columns=[np.nan, 'a'])
print (df)
   NaN  a
0    1  4

print (df.columns.tolist())
[nan, 'a']

df1 = df.rename(columns={np.nan: 'type'})
print (df1)
   type  a
0     1  4

df.columns = df.columns.fillna('type')
print (df)
   type  a
0     1  4
like image 173
jezrael Avatar answered Oct 07 '22 17:10

jezrael


Directly applying .rename still not working in pandas version 0.24.2 as well when nan is in the labels, looks like a bug to me. Note: this label is created by another pandas method in the first place: pd.get_dummies(s,dummy_na=True).

My workaround is to convert the column labels to str first: df.rename(columns=str).rename(columns={'nan':'new_lbl'})

like image 43
tozCSS Avatar answered Oct 07 '22 17:10

tozCSS


Using pandas version 0.25.3 with a nan value in the index, calling df.rename(index={np.nan: 'new_label'}) is not working for me either.

Following tozCSS's suggestion, renaming all index labels to string (albeit all others besides that one were...) and then renaming worked for me:

df.rename(index=str).rename(columns={'nan':'new_lbl'})

Link to documentation: pandas.DataFrame.rename

like image 31
james-bertrand Avatar answered Oct 07 '22 17:10

james-bertrand