python - pandas python 中没有列名

标签 python pandas

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

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

感谢您的帮助。

最佳答案

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

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

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

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

事实上,您可以认为该列已经有了名称——它是整数 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'

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

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

关于python - pandas python 中没有列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14046006/

相关文章:

python - 在 gtk textview 中使用系统等宽字体

python - 为什么生成器表达式这么叫?

python - NoReverseMatch 位于/blog/Django1.9 URL

python - 如何从列中给出的多个标签创建列表

python - 如何根据不同的索引阈值过滤数据帧

python - 在 Python 中为套接字 IO 编写字符串缓冲区的最佳方法是什么?

javascript - 在 python 中,我可以编写 myarray[ :3] to address elements of a list. 是否可以在 javascript 或节点中编写?

python - Pandas 在下周日返回每一行

python - 对于每个数据帧行,获取前 n 个值以及它们出现的列索引

python - 删除非英语行 Pandas