Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas column names to list

Tags:

python

pandas

According to this thread: SO: Column names to list

It should be straightforward to do convert the column names to a list. But if i do:

df.columns.tolist()

I do get:

[u'q_igg', u'q_hcp', u'c_igg', u'c_hcp']

I know, i could get rid of the u and the ' . But i would like to just get the clean names as list without any hack around. Is that possible ?

like image 588
Moritz Avatar asked Nov 25 '14 14:11

Moritz


People also ask

How do I turn a column into a list in Pandas?

tolist() you can convert pandas DataFrame Column to List. df['Courses'] returns the DataFrame column as a Series and then use values. tolist() to convert the column values to list.

How do I get all the columns in a data frame?

To access the names of a Pandas dataframe, we can the method columns(). For example, if our dataframe is called df we just type print(df. columns) to get all the columns of the Pandas dataframe.

How can I see columns in Pandas?

You can use the loc and iloc functions to access columns in a Pandas DataFrame. Let's see how. If we wanted to access a certain column in our DataFrame, for example the Grades column, we could simply use the loc function and specify the name of the column in order to retrieve it.

How do I get only certain columns in Pandas?

To select a single column, use square brackets [] with the column name of the column of interest.


2 Answers

Or, you could try:

df2 = df.columns.get_values()

which will give you:

array(['q_igg', 'q_hcp', 'c_igg', 'c_hcp'], dtype=object)

then:

df2.tolist()

which gives you:

['q_igg', 'q_hcp', 'c_igg']
like image 102
gincard Avatar answered Oct 23 '22 17:10

gincard


The list [u'q_igg', u'q_hcp', u'c_igg', u'c_hcp'] contains Unicode strings: the u indicates that they're Unicode strings and the ' are enclosed around each string. You can now use these names in any way you'd like in your code. See Unicode HOWTO for more details on Unicode strings in Python 2.x.

like image 38
Simeon Visser Avatar answered Oct 23 '22 18:10

Simeon Visser