打印类别列表作为列

Pag*_*Max 4 python list series categories pandas

我正在以熊猫文档为例.让我们说在阅读excel文件后我有一个系列

import pandas as pd
s = pd.Series(["a","b","c","a"], dtype="category")
Run Code Online (Sandbox Code Playgroud)

我知道我可以得到不同的类别

scat=s.cat.categories
print scat
Run Code Online (Sandbox Code Playgroud)

我得到了

Index([u'a', u'b', u'c'], dtype='object')
Run Code Online (Sandbox Code Playgroud)

我想知道什么是使这个列表显示为列的好方法.就像是

a
b
c
Run Code Online (Sandbox Code Playgroud)

我可以u'通过这样做摆脱,np.asarray但仍然没有得到我需要的格式.

Ale*_*der 8

当你说'出现'作为专栏时,我不确定你的意思.

您可以通过以下方式创建列表而不是索引:

>>> s.cat.categories.tolist()
['a', 'b', 'c']
Run Code Online (Sandbox Code Playgroud)

或者您可以使用for循环在列结构中将它们打印出来:

for c in s.cat.categories:
    print c

a
b
c
Run Code Online (Sandbox Code Playgroud)

或者您可以创建一个系列(或数据框):

>>> pd.Series(s.cat.categories)
0    a
1    b
2    c
dtype: object

>>> pd.DataFrame(s.cat.categories)
   0
0  a
1  b
2  c
Run Code Online (Sandbox Code Playgroud)


jez*_*ael 5

我认为这没问题 - 'u'意味着unicode字符串:

s = pd.Series(["a","b","c","a"], dtype="category")
print s
0    a
1    b
2    c
3    a
dtype: category
Categories (3, object): [a, b, c]

scat=s.cat.categories
print scat
Index([u'a', u'b', u'c'], dtype='object')

print scat[0]
a

print type(scat[0])
<type 'str'>   
Run Code Online (Sandbox Code Playgroud)

如果你想要没有循环使用的打印列numpy reshape:

print len(scat)
3
print scat.values.reshape(len(scat),1)
[['a']
 ['b']
 ['c']]
Run Code Online (Sandbox Code Playgroud)