Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python renaming Pandas DataFrame Columns

import pandas as pd
import numpy as np
datain = np.loadtxt(datafile)
df = pd.DataFrame(data = datain, columns = ["t","p","x","y","z"])
avg = df.groupby(["t"], sort=False)["p"].mean().rename(columns={1:"mean"})

This doesn't work, it tells me TypeError: rename() got an unexpected keyword argument "columns". It also doesn't work if I do this,

avg.rename(columns = {1:"mean"}, inplace=True)

I cannot figure out why, all documentation tells me that my columns call is correct. I just want to rename the blank column created by my "mean" call to have a string index. Anyone know why or how to fix this? All examples I've seen follow this format. Thanks.

like image 830
Will Avatar asked Feb 27 '19 18:02

Will


1 Answers

IIUC you could do this

import pandas as pd
df = pd.DataFrame({"a":np.arange(10),
                   "b":np.random.choice(["A","B"],10)})

avg = df.groupby("b", sort=False)["a"].mean()\
        .reset_index(name="mean")

or

avg = df.groupby("b", sort=False)["a"].mean().reset_index()\
        .rename(columns={"a":"mean"})

or

avg = df.groupby("b", sort=False, as_index=False)["a"].mean()\
        .reset_index()\
        .rename(columns={"a":"mean"})
like image 124
rpanai Avatar answered Oct 21 '22 20:10

rpanai