Ojjasvi Puri
Ojjasvi Puri

Reputation: 11

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

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

np.random.seed(1234)

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?

Upvotes: 1

Views: 68

Answers (1)

jezrael
jezrael

Reputation: 862641

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)

Upvotes: 1

Related Questions