pandas column names to list
根据这条线索:so:要列出的列名称
将列名转换为列表应该很简单。但如果我这样做:
| 1 | df.columns.tolist() | 
我确实得到:
| 1 | [u'q_igg', u'q_hcp', u'c_igg', u'c_hcp'] | 
我知道,我可以摆脱u和the。但我只想得到清白的名单,没有任何黑客左右。有可能吗?
或者,您可以尝试:
| 1 | df2 = df.columns.get_values() | 
这将给你:
| 1 | array(['q_igg', 'q_hcp', 'c_igg', 'c_hcp'], dtype=object) | 
然后:
| 1 | df2.tolist() | 
这给了你:
| 1 | ['q_igg', 'q_hcp', 'c_igg'] | 
列表
如前所述,u表示其unicode已转换。无论如何,最干净的方法是将列名转换为ASCII或类似的东西。
| 1 2 3 4 5 | In [4]: cols Out[4]: [u'q_igg', u'q_hcp', u'c_igg', u'c_hcp'] In [5]: [i.encode('ascii', 'ignore') for i in cols] Out[5]: ['q_igg', 'q_hcp', 'c_igg', 'c_hcp' | 
这里的问题是,您将丢失不以ASCII编码的特殊字符。
一个更脏的解决方案是获取列表对象的字符串表示形式并替换u。我不会使用它,但在这种特殊情况下,它可能适合您的需要;-)
| 1 2 3 4 | In [7]: repr(cols) Out[7]:"[u'q_igg', u'q_hcp', u'c_igg', u'c_hcp']" In [11]: x.replace("u","") Out[11]:"['q_igg', 'q_hcp', 'c_igg', 'c_hcp']" | 
参见:https://docs.python.org/2/library/repr.html
如果您只想打印不带引号或Unicode指示器的名称,可以这样做:
| 1 2 | In [19]: print"[" +",".join(df) +"]" [q_igg, q_hcp, c_igg, c_hcp] |