我有一系列的表格:
s = Series([['a','a','b'],['b','b','c','d'],[],['a','b','e']])
看起来像
0 [a, a, b]
1 [b, b, c, d]
2 []
3 [a, b, e]
dtype: object
我想数一数我总共有多少个元素。 我天真的尝试像
s.values.hist()
或
s.values.flatten()
没用。 我做错了什么?
最佳答案
如果我们像最初的问题一样坚持使用 pandas 系列,那么从 Pandas 版本 0.25.0 开始,一个巧妙的选择是 Series.explode()。常规。它向行返回一个分解列表,其中将为这些行复制索引。
问题的原始系列:
s = pd.Series([['a','a','b'],['b','b','c','d'],[],['a','b','e']])
让我们分解它,我们得到一个序列,其中索引是重复的。索引表示原始列表的索引。
>>> s.explode()
Out:
0 a
0 a
0 b
1 b
1 b
1 c
1 d
2 NaN
3 a
3 b
3 e
dtype: object
>>> type(s.explode())
Out:
pandas.core.series.Series
要计算我们现在可以使用 Series.value_counts() 的元素数量:
>>> s.explode().value_counts()
Out:
b 4
a 3
d 1
c 1
e 1
dtype: int64
也包括 NaN 值:
>>> s.explode().value_counts(dropna=False)
Out:
b 4
a 3
d 1
c 1
e 1
NaN 1
dtype: int64
最后,使用 Series.plot() 绘制直方图:
>>> s.explode().value_counts(dropna=False).plot(kind = 'bar')
关于python - 在 pandas 中展平一个系列,即一个元素为列表的系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24027723/