researchnewbie
researchnewbie

Reputation: 100

How to display a specific column's headers name using the panda package in Python

I want to display just the column's header name. I tried using .columns, but that list all the data frame's column headers and I just want to only print the header of the two columns I'm passing.

def test(x, y): # x and y are specific columns within a data frame that is being passed.

   print(x.columns, y.columns) # Runs an error of course, but I want to know how I would display just display their header names.             

So I used panda to create a data frame of a .csv, which could be this:

    num1   num2   num3
0    1      2      3
1    4      5      6
2    7      8      9

So lets say I passed the columns 'num1' and 'num3' as parameters to the function test as x and y. I want to print the names num1 and num3 since those are the header names. How would I go about that?

UPDATE: Okay so, I got the names to display using print(). However, I guess the actual error is when I do plt.xlabel(x.name) & plt.ylabel(y.name). It gives the error: 'str' object has no attribute 'pop'. I thought print() and plt.xlabel() or plt.ylabel() would be treated the same, my apologies.

UPDATE 2: Solved! Thanks guys!

Upvotes: 1

Views: 2975

Answers (2)

Massifox
Massifox

Reputation: 4487

Given the following dataframe:

df = pd.DataFrame([[1,2,3], [4,5,6], [7,8,9]], columns=['num1', 'num2', 'num3'])

Try this code:

def test(x, y):
    print(x.name, y.name)

test(x=df['num1'], y=df['num3'])

gives:

# output: num1 num3

Note: x and y are pandas series, and to get the name of the series (which corrsipsonde the name of the df column) you must use the attribute .name

If I understand your second question correctly, this code is for you:

cols = df.columns

for x, y in zip(cols, cols[1:]):
    test(df[x],df[y])

and gives:

num1 num2
num2 num3

Upvotes: 1

vb_rises
vb_rises

Reputation: 1907

d = {'id': ['x1', 'x2'],'t1': [3,11]}
df = pd.DataFrame(data=d)


def test(x, y): # x and y are specific columns within a data frame that is being passed.
   print(x.name, y.name)
n1 = df['id']
n2 = df['t1']

test(n1,n2)

#output
id t1

Upvotes: 1

Related Questions