从 Pandas 列索引中提取列名

Jas*_*son 3 python-2.7 pandas

我有一个函数,它需要Pandas在散点图上绘制列。我想使用列的名称作为轴标签。这是我的意思的一个例子:

def plotscatter(x,y):
    plt.scatter(x, y)
    plt.xlabel(x)
    plt.ylabel(y)
plotscatter(df['1stcol'],df['2ndcol'])
Run Code Online (Sandbox Code Playgroud)

我只想提取引号中的文本,即 1stcol 和 2ndcol。如果我按原样使用 x 和 y,我会得到列名,后跟所有值作为轴标签。

是否有内置的方法或功能?像 x.columnname()

jor*_*ris 5

您可以使用DataFrame.columns或 为列访问列名Series.name。一个例子:

In [11]: df = pd.DataFrame([[1,2],[2,4]], columns=['1stcol', '2ndcol'])

In [13]: df.columns
Out[13]: Index([u'1stcol', u'2ndcol'], dtype='object')

In [14]: df.columns[0]
Out[14]: '1stcol'

In [16]: df['1stcol'].name
Out[16]: '1stcol'
Run Code Online (Sandbox Code Playgroud)