2016-12-01 447 views
9

我讀了一個csv文件到一個熊貓數據框中,並且想用二進制答案將字符串轉換爲1/0的整數。下面,我展示了其中一個這樣的列(「sampleDF」是熊貓數據框)。是否有一種簡單的方法可以將Pandas數據框中的一列是/否更改爲1/0?

In [13]: sampleDF.housing[0:10] 
Out[13]: 
0  no 
1  no 
2 yes 
3  no 
4  no 
5  no 
6  no 
7  no 
8 yes 
9 yes 
Name: housing, dtype: object 

非常感謝幫助!

+7

'sampleDF.housing.replace(( '是', '否'),(1,0),就地= TRUE)' – AChampion

+0

,沒有工作,謝謝! – Mushu909

回答

3
# produces True/False 
sampleDF['housing'] = sampleDF['housing'] == 'yes' 

上面返回True/False值,它們分別是1/0。布爾支持和函數等。如果你真的需要它是1/0值,你可以使用以下。

housing_map = {'yes': 1, 'no': 0} 
sampleDF['housing'] = sampleDF['housing'].map(housing_map) 
4

嘗試這種情況:

sampleDF['housing'] = sampleDF['housing'].map({'yes': 1, 'no': 0}) 
15

方法1

sample.housing.eq('yes').mul(1) 

方法2

pd.Series(np.where(sample.housing.values == 'yes', 1, 0), 
      sample.index) 

方法3

sample.housing.map(dict(yes=1, no=0)) 

方法4

pd.Series(map(lambda x: dict(yes=1, no=0)[x], 
       sample.housing.values.tolist()), sample.index) 

方法5

pd.Series(np.searchsorted(['no', 'yes'], sample.housing.values), sample.index) 

所有得到

0 0 
1 0 
2 1 
3 0 
4 0 
5 0 
6 0 
7 0 
8 1 
9 1 

定時
給定樣品

enter image description here

定時
長的樣品
sample = pd.DataFrame(dict(housing=np.random.choice(('yes', 'no'), size=100000)))

enter image description here

+0

這是一個很好的深入答案。我甚至不會想到其中的一些。 –

+0

我祝你聖誕快樂!小禮物(3)如果有什麼不妥,那麼對不起!最後的誤解並不好,但我真的不做錯事,也許我可以很快寫出解釋評論......所以祝你好運,謝謝你的幫助! – jezrael

+0

聖誕快樂!不管這個問題如何改變,我希望你和你的家人最好( - : – piRSquared

0
%timeit 
sampleDF['housing'] = sampleDF['housing'].apply(lambda x: 0 if x=='no' else 1) 

1.84毫秒±每個環路56.2微秒(平均值±標準。開發。7點運行時,1000個循環的每個)

替代對象 '是' 1, '否' 以0爲指定的DF柱。

相關問題