如何在 Pandas DataFrame 上添加列标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38655701/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:42:02  来源:igfitidea点击:

how to add columns label on a Pandas DataFrame

pythonpandas

提问by Stefano Fedele

I can't understand how can I add column names on a pandas dataframe, an easy example will clarify my issue:

我不明白如何在 Pandas 数据框上添加列名,一个简单的例子将阐明我的问题:

dic = {'a': [4, 1, 3, 1], 'b': [4, 2, 1, 4], 'c': [5, 7, 9, 1]}
df = pd.DataFrame(dic)

now if I type df than I get

现在如果我输入 df 比我得到

   a  b  c
0  4  4  5
1  1  2  7
2  3  1  9
3  1  4  1

say now that I generate another dataframe just by summing up the columns on the previous one

现在说我只是通过总结前一列的列来生成另一个数据帧

a = df.sum()

if I type 'a' than I get

如果我输入“a”而不是我得到

a     9
b    11
c    22

That looks like a dataframe without with index and without names on the only column. So I wrote

这看起来像一个没有索引且唯一列上没有名称的数据框。所以我写了

a.columns = ['column']

or

或者

a.columns = ['index', 'column']

and in both cases Python was happy because he didn't provide me any message of errors. But still if I type 'a' I can't see the columns name anywhere. What's wrong here?

在这两种情况下,Python 都很高兴,因为他没有向我提供任何错误消息。但是,如果我输入“a”,我在任何地方都看不到列名。这里有什么问题?

采纳答案by ysearka

The method DataFrame.sum()does an aggregation and therefore returns a Series, not a DataFrame. And a Series has no columns, only an index. If you want to create a DataFrame out of your sum you can change a = df.sum()by:

该方法DataFrame.sum()进行聚合,因此返回 a Series,而不是 a DataFrame。并且一个系列没有列,只有一个索引。如果您想从总和中创建一个 DataFrame,您可以a = df.sum()通过以下方式进行更改:

a = pandas.DataFrame(df.sum(), columns = ['whatever_name_you_want'])