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 ?
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.
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.
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.
To select a single column, use square brackets [] with the column name of the column of interest.
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']
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.
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