Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a column name from a Pandas column index

I have a function which takes Pandas columns to be plotted on a scatter graph. I'd like to use the names of the columns as axis labels. Here's an example of what I mean:

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

I'd like to extract just the text in the inverted commas i.e. 1stcol and 2ndcol. If I use x and y as they are I get the column name followed by all of the values as an axis label.

Is there a built-in method or function for this? Like x.columnname()

like image 309
Jason Avatar asked Oct 16 '25 19:10

Jason


1 Answers

You can access the columns names with DataFrame.columns or for a column Series.name. An example:

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'
like image 92
joris Avatar answered Oct 18 '25 11:10

joris