2017-08-05 31 views
0

原始數據幀(DF):選擇後僅選擇數字字段包括含有浮標從熊貓數據幀

 A B 
0 1 green 
1 2 red 
2 s blue 
3 4.3 yellow 
4 b black 

預期數據幀(DF):

 A B 
0 1 green 
1 2 red 
3 4.3 yellow 

嘗試:

既不df[df['A'].astype(str).str.isdigit()]也不df[df['A'].astype(str).str.isdemical()]可以得到預期的結果,但如下:

A  B 
0 1 green 
1 2 red 

希望:

  • 如何得到我想要
  • 解釋爲什麼isdigit()isdemical()失敗

回答

2

嘗試pd.to_numeric(..., errors='coerce')什麼:

In [315]: df[pd.to_numeric(df.A, errors='coerce').notnull()] 
Out[315]: 
    A  B 
0 1 green 
1 2  red 
3 4.3 yellow 

所有非整數值轉換到NaN。之後,使用df.notnull,得到一個布爾值掩碼並且只是索引。


isdigit()isdecimal()都失敗了,因爲它們看起來只有整數。浮動不被認爲是有效的。

+1

我打算用數字和你剛要快! +1 –

1

另一種簡單的方法是isalpha != True

df[df['A'].str.isalpha()!=True] 

df[~df['A'].str.isalpha()] 

regex使用即str.match

df[df['A'].str.match(r'[+-]?([\d]*[.])?[\d]+')] 

以相反的方式去
df[~df['A'].str.match(r'[A-z]')] 

輸出:

 
    A  B 
0 1 green 
1 2  red 
3 4.3 yellow