[英]Changing the column name of dataframe after indexing in python using pandas
嗨,我使用此代码随机用 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")
透视后,我检查的列看起来像
df.columns.to_list()
[('value', 'AGE'), ('value','DATE'),.........,('value','TIME')]
但我希望它们只是 ['AGE', 'DATE',...,'TIME']。
我怎样才能做到这一点?
将参数values
添加到pivot
是更简单的方法:
df.pivot(index = "index", columns = "variable", value='value')
或者:
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.