Home > Blockchain >  Changing the column name of dataframe after indexing in python using pandas
Changing the column name of dataframe after indexing in python using pandas

Time:10-22

Hi I used this code to fill my dataset with NaN values randomly:

total_cells = df.shape[0] * df.shape[1]
df = df.reset_index().melt(id_vars = "index")
df.loc[np.random.randint(0, total_cells, int(total_cells * .25)), "value"] = np.NaN
df.pivot(index = "index", columns = "variable")

After pivot my columns look like when I check

df.columns.to_list()
[('value', 'AGE'), ('value','DATE'),.........,('value','TIME')] 

but I want them to just be ['AGE', 'DATE',...,'TIME'].

How can I do that?

CodePudding user response:

Add parameter values to pivot is simplier way:

df.pivot(index = "index", columns = "variable", value='value')

Or:

df.pivot(index = "index", columns = "variable").droplevel(axis=1, level=0)

CodePudding user response:

plz, try this.

df.pivot(index = "index", columns = "variable", columns='value')
  • Related