![](/img/trans.png)
[英]Drop consecutive duplicates in Pandas dataframe if repeated more than n times
[英]find a number that is repeated between 2 columns, n consecutive times
我想找到 n 次(例如 500 次)在文本文件的兩列之間重復的行數。
我的文本文件是這樣的(有很多行):
0.85 0.00 1
0.85 0.45 2
0.97 0.14 3
0.91 0.05 4
0.97 0.97 5
0.0 0.1 6
0.45 0.0 7
0.0 0.0 8
0.0 0.0 9
0.0 0.0 10
我的腳本嘗試是:
with open('list.txt') as f:
c = 0
for i in f:
for w in i:
if w[0] == w[1]:
c+=1
if c == 500:
print(i-498)
break
else:
c=0
print(i)
我想要行數(第 3 列),例如數字 0 在第 1 列和第 2 列中至少連續重復 500 次。輸出將是這樣的(假設從第 8 行開始,0 重復 500 次第 1 列和第 2 列之間)
0.0 0.0 8
0.0 0.0 9
0.0 0.0 10
你能幫我修一下嗎? 非常感謝
您需要在比較之前拆分每一行並將值轉換為浮點數。
試試這個代碼。 為了測試,它搜索 2 個連續的行。 將其更改為 500 以供您運行。
ss = '''
0.85 0.00 1
0.85 0.45 2
0.97 0.14 3
0.91 0.05 4
0.97 0.97 5
0.0 0.1 6
0.45 0.0 7
0.0 0.0 8
0.0 0.0 9
0.0 0.0 10
'''.strip()
with open ('list.txt','w') as f: f.write(ss) # write test file
#############################
rep = 2 # change to 500
with open('list.txt') as f:
c = 0
for i in f:
w = [float(n) for n in i.strip().split()]
if w[0] == w[1]:
c+=1
if c == rep:
print('>>> line', int(w[2]))
break
else:
c=0
print(i.strip())
輸出
0.85 0.00 1
0.85 0.45 2
0.97 0.14 3
0.91 0.05 4
0.0 0.1 6
0.45 0.0 7
>>> line 9
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.