如何循环一个系列并将值多次添加到新列表中?

问题描述

我有一个像下面这样的系列

import pandas as pd 
a = pd.Series(['a','b','c','d','e'])

我想循环这个系列并附加到新列表和我的预期结果

new_lst = [a,a,b,c,d,e,e]

这是我以前试过的

new_lst = []
for i in a:
    new_lst.append(i*5)

但我得到了结果

['aaaaa','bbbbb','ccccc','ddddd','eeeee']

解决方法

>>> list(a.repeat(5))
['a','a','b','c','d','e','e']
, i 循环中的

for 是一个 str 对象。当您将 strint 相乘时,您会多次重复 str。在您的情况下,i*5 将字符串 i 重复 5 次。

一个简单的解决方案是简单地将字符串附加 5 次。例如,

new_lst = []
for i in a:
    new_lst.append(i)
    new_lst.append(i)
    new_lst.append(i)
    new_lst.append(i)
    new_lst.append(i)

只需将对象附加 5 次。

如果你想要一个更好看的解决方案,你可以用另一个 append 循环重复 for 语句 5 次:

new_lst = []
for i in a:
    for j in range(5):
        new_lst.append(i)