#dataframe a, b:
a = [1,2,3,7,2,6,4]
b = [[0.7, 1.5],[1.6, 2.9],[3, 4.7],[4.8, 8]]
# b[k][0] <= a[i] <= b[k][1]
#I need to create a dataframe like:
c = [[0.7,1,1.5],[1.6, 2,2.9],[3,3,4.7],[4.8,7,8],[1.6,2,2.9],[4.8,6,8],[3,4,4.7]];
条件:添加两个新列,我不能使用循环
答案 0 :(得分:2)
使用列表理解:
print([[x, y, z] for y, (x, z) in zip(a, b)])
输出:
[[0.7, 1, 1.5], [1.6, 2, 2.9], [3, 3, 4.7], [4.8, 7, 8]]
答案 1 :(得分:0)
看到输入数据,我将假定此前提条件(OP提到了其中的一部分):
对于所有k,k
b [k] [0] <= b [k] [1] 对于所有k,k
b [k] [1] <= b [k + 1] [0] 对于任何i,i
存在这样的i,k:
b [k] [0] <= a [i] <= b [k] [1]
使用递归:
def rec_a(a: list, i: int, b: list):
if i >= len(a):
return []
else:
# Put result of rb in a list in order to extend it
rb = [rec_b(a[i], b, 0)]
# Get rest of the result
ra = rec_a(a, i+1, b)
# Merge the rest of the result with the current one
rb.extend(ra)
return rb
def rec_b(elem: float, b: list, k: int):
if k >= len(b):
return None
elif b[k][0] <= elem <= b[k][1]:
return [b[k][0], elem, b[k][1]]
else:
return rec_b(elem, b, k+1)
def rec(a: list, b: list):
"""
PRECONDITION:
For all k, k < len(b):
b[k][0] <= b[k][1]
and for all k, k < len(b) - 1:
b[k][1] <= b[k+1][0]
and for any i, k that i < len(a) and k < len(b):
exists such i, k that:
b[k][0] <= a[i] <= b[k][1]
"""
return rec_a(a, 0, b)
运行
A = [1,2,3,7,2,6,4]
B = [[0.7, 1.5],[1.6, 2.9],[3, 4.7],[4.8, 8]]
print(rec(A, B))
意见:
[[0.7, 1, 1.5], [1.6, 2, 2.9], [3, 3, 4.7], [4.8, 7, 8], [1.6, 2, 2.9], [4.8, 6, 8], [3, 4, 4.7]]