在熊猫python中没有列名

时间:2020-12-30 22:59:12

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.0 doesn't work nor df[0,'']. df.ix[0,0] does work.

关于熊猫的基本问题。我有一个带有数据点的1x1 dataframe,并且没有列标题(目前)。df[0,0]不起作用,因为我认为它需要一个列名。此外,df。0和df都不行[0,"]df。第九(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?

一般来说,我需要一个列名吗?在熊猫数据中使用列名是最好的做法吗?如果我的sql查询没有列标题,那么最好在此时添加它们吗?

Thanks for the help.

谢谢你的帮助。

1 个解决方案

#1


8  

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.ix just as before, though:

您仍然可以使用DataFrame。就像以前一样:

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

#1


8  

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.ix just as before, though:

您仍然可以使用DataFrame。就像以前一样:

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