pandas 如何在熊猫数据框中添加标题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33702237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a header in pandas dataframe
提问by Ashwin Jayarama
I have a pandas dataframe with headers id,n and t containing duplicate id and after calling groupby and then size() and extra column with no header is generated given below.Now how do I add an extra column header 'count' associated with the values of the 4th column values so that it becomes ['id','n','t','count']
我有一个包含重复 id 的标题 id、n 和 t 的Pandas数据框,在调用 groupby 之后,然后 size() 和没有标题的额外列在下面给出。现在我如何添加一个额外的列标题“计数”与第 4 列值的值,使其变为 ['id','n','t','count']
id n t
7 2 Y 4
7 2 N 6
8 3 Y 2
8 9 N 3
9 1 Y 5
9 6 N 7
编号
7 2 Y 4
7 2 N 6
8 3 Y 2
8 9 N 3
9 1 Y 5
9 6 N 7
回答by Ashwin Jayarama
As @EdChum mentioned reset_index
has to be called on groupby
and then rename. Pandas generates a header 0 for the extra column
正如@EdChum 提到的reset_index
,必须调用groupby
然后重命名。Pandas 为额外的列生成标题 0
df = df.reset_index()
df.rename(columns={0:'count'}, inplace=True)