Set pandas DataFrame index name

I have a pandas dataframe:

    ''     count
sugar      420
milk       108
vanilla    450
...

There is no heading in the first column, and I would like to name it: "component".

I created a dataframe from the csv file:

df = pd.read_csv('./data/file_name.csv', index_col=False, encoding="ISO-8859-1")  
df = df['ingredient_group']  #selecting column 
df = df.value_counts()       #calculating string occurance which return series obj
df = pd.DataFrame(df)        #creating dataframe from series obj

How do I give the name "ingredient" to the first column that currently doesn't have a name?

I already tried:

df_count.rename(columns={'': 'ingredient'}, inplace=True)

df = pd.DataFrame(df, columns = ['ingredient','count']

How can I prevent this?

''        count
ingredient  ''
sugar      420
milk       108
vanilla    450
...
+4
source share
2 answers

if ingredients is the name of the index, you can set it

df.index.name='ingredient'

"" , . , . , , .

df['ingredient']=df.index
df = df.reset_index(drop=True)
+7

:

cols_ = df.columns
cols[0] = 'ingredient'
df.columns = cols_
+1

All Articles