2016-07-27 94 views
-1

我正在嘗試編寫一個for循環來遍歷我的索引,並且只保留那些有重複的索引。在Python中迭代索引

我現在的數據幀由兩個合併在一起

    0.0102700  0.0308099  0.0616199  0.123240 \ 
5000000000010 4.330760e-05 4.442720e-05 9.232970e-05 1.994190e-04 
5000000000238 6.006910e-04 6.041130e-04 1.220220e-03 2.500240e-03 
... 

   0.00902317  0.0270695  0.0451159  0.0631622 \ 
5000000000010 6.962980e-05 7.063750e-05 7.165970e-05 7.269680e-05 
5000000000234 4.638970e-04 4.716010e-04 4.794320e-04 4.873930e-04 

New = pd.concat([SFR_low, SFR_high]) 
New = New.sort_index() 
print(New) 

       0.00902317  0.0102700  0.0270695  0.0308099 \ 
5000000000010 6.962980e-05   NaN 7.063750e-05   NaN 
5000000000010   NaN 4.330760e-05   NaN 4.442720e-05 
5000000000081 6.299210e-05   NaN 6.299320e-05   NaN 
5000000000082   NaN 8.176550e-04   NaN 8.172630e-04 

我需要一個新的數據幀,只保留具有重複索引的行。

+0

請編輯的問題,並添加您的代碼和數據框(或它的一部分) – danielhadar

+0

只是這樣做了,但我還沒有任何代碼,因爲這些文件剛剛被讀入。 – cmf05

+0

您想保留值,行或列嗎?並重覆在哪裏?在同一行,列或整個表中?並且請嘗試一下,如果你失敗了,那麼請重新回答這個問題。這可能會幫助你解決所需的代碼,以消除重複http://chrisalbon.com/python/pandas_dataframe_count_values.html一些代碼來檢查DataFrame上的頻繁性。祝你好運。 – ElMesa

回答

0

使用Index.duplicated與參數keep=False

print (df.index[df.index.duplicated(keep=False)]) 
Int64Index([1000, 1000, 1002, 1002], dtype='int64') 


for i in df.index[df.index.duplicated(keep=False)]: 
    print (i) 
1000 
1000 
1002 
1002 

如果需要過濾行與複製指數,使用boolean indexing

print (New.index.duplicated(keep=False)) 
[ True True False False] 

print (New[New.index.duplicated(keep=False)]) 
       0.00902317 0.0102700 0.0270695 0.0308099 0.0451159 \ 
5000000000010   NaN 0.000043  NaN 0.000044  NaN 
5000000000010  0.00007  NaN 0.000071  NaN 0.000072 

       0.0616199 0.0631622 0.123240 
5000000000010 0.000092  NaN 0.000199 
5000000000010  NaN 0.000073  NaN 
0
li = [1000,1000,1001,1002,1002] 
for i in li: 
    temp = i 
    count = 0 
    for j in li: 
     if j is temp: 
      count +=1 
    if count > 1: 
     print i 

這解決了你的要求嗎?

+0

OP使用'pandas'不是列表,這個答案與OP的問題無關 – EdChum

0

第一次嘗試前問一些代碼: 有很多重複的問題

a = [1000,1000,1001,1002,1002] 
c = [x for x in a if a.count(x) > 1] 
print c