[英]python making a new list from two lists, second list says how many times to repeat the elements in the first list
I have data like this: 我有这样的数据:
df
col1 col2
3 4
1 2
2 2
4 7
Right now the data is a pandas df, but I could conceivably make the columns lists or whatever is needed. 现在,数据是pandas df,但我可以想象得出列列表或所需的任何内容。
I want the output to be this. 我希望输出是这个。
[3,3,3,3,1,1,2,2,4,4,4,4,4,4,4]
if col1 and col2 can be represented as lists then : 如果col1和col2可以表示为列表,则:
ans = []
for i in xrange(len(col1)):
ans+=[col1[i]]*col2[i]
print ans
Assuming the len of col1 and col2 would be equal 假设col1和col2的len相等
([ a for a, b in zip(df.col1,df.col2) for _ in xrange(b)])
[3, 3, 3, 3, 1, 1, 2, 2, 4, 4, 4, 4, 4, 4, 4]
Or using a normal loop: 或使用普通循环:
res = []
for a, b in zip(df.col1, df.col2):
res.extend([a]* b)
print(res)
[3, 3, 3, 3, 1, 1, 2, 2, 4, 4, 4, 4, 4, 4, 4]
Or simply use repeat
: 或者简单地使用
repeat
:
print(df.col1.repeat(df.col2).tolist())
[3, 3, 3, 3, 1, 1, 2, 2, 4, 4, 4, 4, 4, 4, 4]
Here's another 这是另一个
>>> sum(([x]*y for (x, y) in zip(col1, col2)), [])
[3, 3, 3, 3, 1, 1, 2, 2, 4, 4, 4, 4, 4, 4, 4]
In [218]: col1 = [3,1,2,4]
In [219]: col2 = [4,2,2,7]
In [220]: list(itertools.chain.from_iterable(itertools.repeat(n,k) for n,k in zip(col1, col2)))
Out[220]: [3, 3, 3, 3, 1, 1, 2, 2, 4, 4, 4, 4, 4, 4, 4]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.