2017-08-29 122 views
1

我有一個包含字符串值和布爾值的列的pandas數據框。由於這種差異,該列的dtype推斷爲'object'。當我在這個列上運行.str.strip()時,它將所有的布爾值都變成NaN。有誰知道我可以如何防止這種情況?我可以用布爾值變成字符串,但是南?從piRSquared在pandas DF上打印空白列將bool值轉換爲NaN

回答

3

借款DF:

首先將所有值string,然後帶:

df['A'] = df['A'].astype(str).str.strip() 
print (df) 
     A 
0  a 
1  b 
2 True 
3 False 
4 True 

如果需要混合類型 - 布爾值與字符串添加combine_first用於替換NaN s到boolean

df['A'] = df['A'].str.strip().combine_first(df.A) 
print (df) 
     A 
0  a 
1  b 
2 True 
3 False 
4 True 

如果需要轉換所有列:

df = df.astype(str).applymap(lambda x: x.strip()) 

或者:

df = df.astype(str).apply(lambda x: x.str.strip()) 
+0

工作我得到了一個: AttributeError的: '海峽' 對象有沒有屬性 '海峽'。但我改變了:'df = df.astype(str).apply(lambda x:x.strip())'這似乎是工作。謝謝! – purplefloyd

+0

我編輯一列的答案,所有列需要'df = df.astype(str).apply(lambda x:x.str.strip())' – jezrael

+0

@piRSquared - 你確定嗎? – jezrael

3

設置

df = pd.DataFrame(dict(A=[' a', ' b ', True, False, 'True'])) 

選項1個
使用pd.Series.str.strip串訪問方法與fillna

df.A.str.strip().fillna(df.A) 

0  a 
1  b 
2  True 
3 False 
4  True 
Name: A, dtype: object 

注:
typestrbool

df.A.str.strip().fillna(df.A).apply(type) 

0  <class 'str'> 
1  <class 'str'> 
2 <class 'bool'> 
3 <class 'bool'> 
4  <class 'str'> 
Name: A, dtype: object 

選項2
使用pd.Series.replace

df.A.replace('^\s+|\s+$', '', regex=True) 

0  a 
1  b 
2  True 
3 False 
4  True 
Name: A, dtype: object 

混合類型也保存在這裏。


我們可以用pd.DataFrame.replace對整個數據幀

df.replace('^\s+|\s+$', '', regex=True) 

     A 
0  a 
1  b 
2 True 
3 False 
4 True 
+0

當你們這麼快時,我該如何回答問題? –

+1

@cᴏʟᴅsᴘᴇᴇᴅ[** NoSympathy **](https://stackoverflow.com/users/4909087/c%E1%B4%8F%CA%9F%E1%B4%85s%E1%B4%98%E1%B4 %87%E1%B4%87%E1%B4%85?tab =聲望)( - ; – piRSquared