我使用一些数据库并使用 Pandas 进行分析。以下条目应该是数组,但 Pandas 将它们“视为”对象。如何将每一行(条目)转换为数组或数字列表?
我的任务是计算零“[0]”在此列中出现的次数(应该是 6)。
df['q3']
Out[26]:
7838 [1, 2, 3]
7790 [0]
7853 [1, 2, 3, 4]
7889 [1, 2]
7928 [1, 2, 3]
7847 [1]
7884 [1]
7826 [1]
22101 [1]
7784 [1]
7795 [1]
7743 [1, 3, 4]
7878 [1, 2, 3, 4]
7761 [0]
7771 [1, 3]
7901 [1, 3]
7873 [3, 2, 1, 4]
8424 [1]
7887 [0]
7969 [1, 2]
8020 [0]
7895 [0]
7834 [1, 2, 3]
7947 [1]
7822 [2, 3, 4]
7970 [0]
8124 [1]
7916 [1, 2]
Name: q3, dtype: object
In [27]: df['q3'].values
Out[27]:
array([[u'1', u'2', u'3'], [u'0'], [u'1', u'2', u'3', u'4'], ..., [u'0'],
[u'1'], [u'1', u'2']], dtype=object)
请您参考如下方法:
看来你可以使用:
from itertools import chain
from collections import Counter
#convert values to ints
df.q3 = df.q3.apply(lambda x: [int(y) for y in x])
#flat columns to list
a = list(chain.from_iterable(df.q3))
#print (a)
#count all ints
b = Counter(a)
print (b)
Counter({1: 21, 2: 10, 3: 10, 0: 6, 4: 5})
print (b[0])
6
