简体   繁体   English

使用pandas在python中建立索引后更改数据框的列名

[英]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:嗨,我使用此代码随机用 NaN 值填充我的数据集:

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'].但我希望它们只是 ['AGE', 'DATE',...,'TIME']。

How can I do that?我怎样才能做到这一点?

Add parameter values to pivot is simplier way:将参数values添加到pivot是更简单的方法:

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

Or:或者:

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

lz,试试这个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM