2013-08-17 164 views
2

我使用的是熊貓系列其中包括號碼清單中,用文字爲索引:如何有條件地選擇從熊貓系列項目

$10    [1, 0, 1, 1, 1, 1, 1] 
$100      [0, 0, 0] 
$15        [1] 
$19       [0, 0] 
$1?       [1, 1] 
$20       [0, 1, 1] 
$20-$40       [0] 

我嘗試寫一些簡單的代碼創建一個新的只包含含有長度爲'n'或更大的列表的項目。

有點像列表理解系列。

感謝所有幫助

回答

2

應避免在Series對象使用list S,但你可以做什麼你問這樣的:

編輯:用法

# DON'T use `eval` in production I'm just using it for convenience here 
In [7]: s = read_clipboard(sep=r'\s{2,}', index_col=0, header=None, squeeze=1).map(eval) 

In [8]: s 
Out[8]: 
0 
$10  [1, 0, 1, 1, 1, 1, 1] 
$100     [0, 0, 0] 
$15       [1] 
$19      [0, 0] 
$1?      [1, 1] 
$20     [0, 1, 1] 
$20-$40      [0] 

In [20]: n = 3 

In [21]: s.map(len) >= n 
Out[21]: 
0 
$10   True 
$100  True 
$15  False 
$19  False 
$1?  False 
$20   True 
$20-$40 False 
Name: 1, dtype: bool 

In [22]: s[s.map(len) >= n] 
Out[22]: 
0 
$10  [1, 0, 1, 1, 1, 1, 1] 
$100    [0, 0, 0] 
$20     [0, 1, 1] 
Name: 1, dtype: object 

您不應在Series對象中使用list s,因爲它們是引擎蓋下的object陣列,而不是均勻類型其中Series可以利用numpy的速度。

+0

的感謝!我實際上已將它轉換爲列表字典中的一系列對象。爲什麼最好不要使用一個系列?並且解決方案與列表字典相同嗎? –

+1

這並不是說使用'Series'就是「壞」,這是因爲當你將任意對象放入'Series'中時,它們要比擁有均勻類型的'Series'慢得多。 –

0

試試這個:

s[s.map(len) >= n]