I have a pandas dataframe like this:
'' count sugar 420 milk 108 vanilla 450 ...
The first column has no header and I would like to give it the name: 'ingredient'.
I created the dataframe from a 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 assign the name 'ingredient' to the first column which has currently no name?
I already tried:
df_count.rename(columns={'': 'ingredient'}, inplace=True) df = pd.DataFrame(df, columns = ['ingredient','count']
How do I prevent this from happening?
'' count ingredient '' sugar 420 milk 108 vanilla 450 ...
Pandas Series: rename() functionThe rename() function is used to alter Series index labels or name.
Use pandas. DataFrame. rename_axis() to set the index name/title, in order to get the index use DataFrame.index.name property and the same could be used to set the index name as well.
if ingredients is the name of the index then you can set it by
df.index.name='ingredient'
With the current solutions you have 'ingredient' as name of the index, which is printed in different row to that of column names. This cannot be changed as is. Try the modified solution below, here the index is copied on to a new column with column name and the index replaced with sequence of numbers.
df['ingredient']=df.index df = df.reset_index(drop=True)
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