2017-06-23 68 views
1

這是我的代碼,其搜索數據幀的一列,並返回,如果要求得到滿足的值:環打破:Python中,熊貓

import pandas as pd 
df=pd.read_csv("cl.csv") 
count=0 
print(len(df.sl_no)) 
print(len(df.sn_compare)) 
for i in range(len(df.sn_compare)): 
    if df.sn_compare[i] in df.sl_no: 
     print(df.margin[i]) 
     count=count+1 

print(count) 

輸出:

8258 
8258 
0.036621541 
. 
. 
. 
0.036621541 
0.043934426 
0.063724333 
3770 

爲什麼循環在達到3770後停止,理想情況下我希望它搜索所有8259行?

+5

也許是因爲'df.sn_compare'中的'3770'條目在'df.sl_no'中? –

+1

只有滿足condifiton時,纔會提升計數器變量。所以病情滿足3770次。他仍在尋找一切。將count = count + 1放在if語句上方的行中,並檢查結果。 – Secespitus

+0

如果'df.sl_no'中的df.sn_compare [i]只加1'count' –

回答

1

考慮下面的例子(我沒有添加保證金列,雖然)。但是對於for循環,它會檢查列值是否包含在其他列值中,所以添加.values我不知道它是否會是相同的情況,但在這種情況下,如果我不那麼,它將返回0) 。

輸出的 df
import pandas as pd 

df = pd.DataFrame({'sl_no':[1,2,3], 'sn_compare':[4,5,3]}) 
print(df) 

 sl_no sn_compare 
0  1   4 
1  2   5 
2  3   3 

現在,

print(len(df.sl_no)) 
print(len(df.sn_compare)) 
count=0 

for i in range(len(df.sn_compare)): 
    if df.sn_compare[i] in df.sl_no.values: 
     #print(df.margin[i]) 
     count=count+1 

print('Count is: ', count) 

輸出:

3 
3 
Count is: 1 

輸出,用於計數將在1因爲只有3匹配,所以count變爲1.

+0

我把計數放在循環中,因爲我想計算滿足條件的次數。問題是,計數應該理想報告一個數字大約5000. –

+0

@RishabhKumar它會幫助,如果你使用'.values'比較?即如果df。sn_compare [i]在df.sl_no.values:' – 0p3n5ourcE

+0

謝謝,df.sl_no.values排序我的問題。 –

0

問題是,只有當條件滿足時纔會遞增計數器變量。這意味着您的3770結果意味着該條件滿足3770次。它沒有說明被搜索的行數量。請嘗試以下操作:

import pandas as pd 
df=pd.read_csv("cl.csv") 
count=0 
print(len(df.sl_no)) 
print(len(df.sn_compare)) 
for i in range(len(df.sn_compare)): 
    if df.sn_compare[i] in df.sl_no: 
     print(df.margin[i]) 
    count=count+1 

print(count) 

區別在於計數器變量的增量具有不同的縮進。它在比較之外,因此對每一行都執行。

+0

我把計數放在循環中,因爲我想計算滿足條件的次數。問題是計數理想情況下應報告5000左右的數字。 –

+0

@RishabhKumar這是應該編輯到您的問題中的重要信息。目前你只會說「爲什麼循環在達到3770後停止,理想情況下我希望它搜索所有8259行?」而答案就是它似乎不會停止並搜索所有行。 – Secespitus