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
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
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'})
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With