簡體   English   中英

計算熊貓系列中存儲的數組中的各個值

[英]Count the individual values within the arrays stored in a pandas Series

這是設置階段的簡單示例:

import pandas as pd
import numpy as np

example_series = pd.Series([np.arange(5), 
                            np.arange(15), 
                            np.arange(12), 
                            np.arange(7), 
                            np.arange(3)])
print example_series

0                                      [0, 1, 2, 3, 4]
1    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...
2               [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
3                                [0, 1, 2, 3, 4, 5, 6]
4                                            [0, 1, 2]

我有一個pandas系列(example_series),其中包含一堆數組。 我正在嘗試計算每個數字出現在系列中的實例數。 因此,我希望返回如下所示的內容:

# Counts = 
0:5
1:5
2:5
3:4
4:4
5:3
#...and so on

而且我更希望它返回一個Series,但是如果有其他事情也可以。 這似乎很簡單,但我無法弄清楚。 我將在下面發布一些失敗的嘗試。

# None of these work
example_series.count(0)
example_series.count(lambda x: x == 0)
example_series[example_series == 0]
example_series.unique()

謝謝你的幫助!

展平列表,然后使用value_counts()

pd.Series([item for sublist in example_series for item in sublist]).value_counts()

2     5
1     5
0     5
4     4
3     4
6     3
5     3
11    2
10    2
9     2
8     2
7     2
14    1
13    1
12    1

不確定Pandas的語法是什么。 但是,純粹的numpy解決方案會很快,那就是使用np.flatten()展平數組集合,然后調用直方圖函數。 結果將返回一個numpy數組,可以將其包裝為一行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM