2017-04-08 53 views
1

如何檢查我的數據框中的每個熊貓行以查看該行是True還是False?在這裏,我想打印'是',如果df ['check']爲真。如何檢查熊貓數據框的真或假 - Python

import pandas as pd 
import numpy as np 

num = [10,20,30,40,30,20,30,40,50,60,70,80,90] 
ind = [0,1,2,3,4,5,6,7,8,9,10,11,12] 

df = pd.DataFrame({'Price': num}, index = ind) 

df['check'] = (df['Price'] > 30) 

if df['check'] == True: 
    print('Yes') 
+0

只是出於好奇:你想知道(一)如果任何行是真實的,(二)行數是真實的,或(三)確切的行是真? – DyZ

回答

2

不知道爲什麼你要做到這一點......但使用itertuples

for row in df.itertuples(): 
    if row.check: 
     print('Yes') 

Yes 
Yes 
Yes 
Yes 
Yes 
Yes 
Yes 

您可以map

df.check.map({True: 'Yes', False: ''}) 

0   
1   
2   
3  Yes 
4   
5   
6   
7  Yes 
8  Yes 
9  Yes 
10 Yes 
11 Yes 
12 Yes 
Name: check, dtype: object 

即使assign你的價值觀地圖它回到專欄

df.assign(mapped=df.check.map({True: 'Yes', False: ''})) 

    Price check mapped 
0  10 False  
1  20 False  
2  30 False  
3  40 True Yes 
4  30 False  
5  20 False  
6  30 False  
7  40 True Yes 
8  50 True Yes 
9  60 True Yes 
10  70 True Yes 
11  80 True Yes 
12  90 True Yes 

您可以使用pd.DataFrame.where這使該值時,第一個參數的計算結果爲True並與第二個參數時False逐漸填滿。如果第二個參數沒有通過,則放置np.nan

df.Price.where(df.check, -99) 

0 -99 
1 -99 
2 -99 
3  40 
4 -99 
5 -99 
6 -99 
7  40 
8  50 
9  60 
10 70 
11 80 
12 90 
Name: Price, dtype: int64 

姐姐方法是mask它執行相反。保持第一個參數是False。這是一個等價的語句

df.Price.mask(~df.check, -99) 

0 -99 
1 -99 
2 -99 
3  40 
4 -99 
5 -99 
6 -99 
7  40 
8  50 
9  60 
10 70 
11 80 
12 90 
Name: Price, dtype: int64 
+0

謝謝我只是想更好地瞭解熊貓的工作原理。我正在玩使用熊貓狀態邏輯的想法。而不是打印,我會設置一個數字== 1. np.where(df ['check']> 30,1,-1)的問題是我想保持我的號碼爲1,直到發生另一個事件。只要語句爲false,np.where就會將其設置回-1。 – BillyRay

+1

@BillyRay我給你一些更多的例子。 – piRSquared

+1

@BillyRay不要忘記接受答案,如果它回答你的問題。 – piRSquared