pandas python中没有列名

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

No Column Names in pandas python

pythonpandas

提问by user1911092

Basic question on a pandas dataframe. I have a 1x1 dataframe with a datapoint and there are no column headers (currently). df[0,0]does not work because I think it is expecting a column name. In addition, df.0doesn't work nor df[0,'']. df.ix[0,0]does work.

关于熊猫数据框的基本问题。我有一个带有数据点的 1x1 数据框,并且没有列标题(当前)。 df[0,0]不起作用,因为我认为它需要一个列名。此外,df.0不起作用也不df[0,'']. df.ix[0,0]确实有效。

In general, am I required to have a column name? Is it a best practice to use column names with pandas dataframes? If my sql query does not have column headers, is it best to add them at that point?

一般来说,我需要有一个列名吗?将列名与 Pandas 数据框一起使用是最佳实践吗?如果我的 sql 查询没有列标题,最好在那时添加它们吗?

Thanks for the help.

谢谢您的帮助。

采纳答案by Aman

Nope, you're not required to assign column names, nor do you need them to access any element.

不,您不需要分配列名称,也不需要它们来访问任何元素。

In [12]: df = pd.DataFrame([0])

In [13]: df.ix[0,0]
Out[13]: 0

In [14]: df[0][0]
Out[14]: 0

In fact, you can think of the column already having a name -- it is the integer 0. Look at what happens when you provide a name

事实上,你可以认为列已经有了一个名字——它是整数 0。看看当你提供一个名字时会发生什么

In [15]: df    #Before naming the column
Out[15]:
   0
0  0

In [16]: df.columns = ['ColA']
In [17]: df    #Renamed
Out[17]:
   ColA
0     0

In [18]: df['ColA'][0]    #Now you can access the column using the new name
Out[18]: 0

In [19]: df[0][0]         #... but trying the old name will not work
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)

KeyError: 'no item named 0'

You can still use DataFrame.ixjust as before, though:

不过,您仍然可以DataFrame.ix像以前一样使用:

In [20]: df.ix[0,0]
Out[20]: 0