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()
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With