Chicrala
Chicrala

Reputation: 1054

Is there any difference between using Dataframe.columns and Dataframe.keys() to obtain the column names?

For the sake of curiosity is there any practical difference between getting the column names of a DataFrame (let's say df) by using df.columns or df.keys()?

I've checked the outs by type and it seems to be exactly the same. Am I missing something or these two methods are just as redundant as it seems? Is one more appropriate to use than the other?

Thanks.

Upvotes: 4

Views: 2501

Answers (2)

Marcos
Marcos

Reputation: 136

Doesn't look like there's a practical difference and if there is, I'd really like to know what it is. You probably saw in the documentation that DataFrame.columns has the column labels and it is an axis property and DataFrame.keys gets the info axis. I would think that since the former is an attribute or reference and the latter a callable method, the method takes a little more time to execute. I have not tested this but I'm pretty sure that, even if there's a difference, it is not significant. Also they both return the same type:

>>> type(data.columns)
<class 'pandas.core.indexes.base.Index'>
>>> type(data.keys())
<class 'pandas.core.indexes.base.Index'>

Upvotes: 4

hesham ahmed
hesham ahmed

Reputation: 143

one difference I noticed That you can Use .keys() with Series but You can not use .columns with Series .

Upvotes: 5

Related Questions