I want to use for loops to find the minimal differences for each three elements by python2.7
This is my test.csv data
E1-2 u7 4
E1-2 u7 7
E1-2 u7 8
F(1)-1 u7 3
F(1)-1 u7 9
F(1)-1 u7 8
.. .. ..
and I want to get the following results
E1-2 u7 7
E1-2 u7 8
F(1)-1 u7 8
F(1)-1 u7 9
.. .. ..
Because in group "E1-2", the minimal difference element is 7 and 8
8-4=5
8-7=1 # the minimal difference
7-4=3
This is my cold, but have some problem. Who can help me modify it? Thanks.
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)`
def mins (datas):
mi=min(pairwise(sorted(datas)), key=lambda x: x[1] - x[0])
return list(mi)`
import pandas as pd
qrt=pd.read_csv("test.csv")
def cul(dat,sam):
#results=pd.DataFrame()
a=dat.iloc[0:2]
b=pd.Series(mins(dat[sam].tolist()))
a.loc[:,'D']=b
return a`
for i in range(0,len(qrt["Ct"])-1,3):
results=pd.DataFrame()
group=qrt[i:i+3]
c=cul(group,"Ct")
results=results.append(c)
print results.head()
The output:
Sample Detector Ct D
0 E1-2 u7 4 7
1 E1-2 u7 7 8
Sample Detector Ct D
3 F(1)-1 u7 3 NaN
4 F(1)-1 u7 9 NaN
from collection import defaultdict
import itertools
import csv
d = defaultdict(list)
with open("test.csv", newline='') as f:
r = csv.reader(f)
for row in r:
row[2] = float(row[2])
d[row[0]].append(row)
for k, v in d.items():
a, b = min(itertools.combinations(v, 2), key=lambda x: abs(x[0][2]-x[1][2]))
print(a)
print(b)
We'll use itertools.combinations
to find all the pairs of elements, then find the pair that gives us the minimum difference and print each element in that pair. You can replace those print
s with whatever you want to do with that data
data = [("a", 3), ("a", 5), ("a", 8), ("b", 18), ("b", 13), ("b", 19)]
indexes = set(index for index, _ in data)
index_values = {index:[value for i, value in data if i == index] for index in indexes}
from itertools import combinations
def difference(pair):
x, y = pair
return abs(x - y)
def smallest_difference(values):
min_diff, min_pair = min((difference(pair), pair) for pair in combinations(values,2))
return min_pair
index_min_pairs = {index:smallest_difference(values) for index, values in index_values.items()}
answer = [(index, min_value) for index in index_min_pairs for min_value in index_min_pairs[index]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.