我有一个看起来像这样的 df:
col1 col2
value test1
value test2
value test3
value test4
value test5
我想像这样重复重命名列表中的 col1:
lst = ['new1','new2','new3','new4','new5']
col1 col2
new1 test1
new2 test2
new3 test3
new4 test4
new5 test5
我需要列表为 col1 中的所有行重复。
我试过这个:
df = df.set_index('col1')
df = df.rename(index={'value':['new1','new2','new3','new4','new5']})
但这会将整个列表传递到 col1 的每一行,如下所示:
col1 col2
['new1','new2','new3','new4','new5'] test1
['new1','new2','new3','new4','new5'] test2
['new1','new2','new3','new4','new5'] test3
['new1','new2','new3','new4','new5'] test4
['new1','new2','new3','new4','new5'] test5
最佳答案
赋值
这仅适用于 OP 的示例,其中 lst
长度与数据帧 df
df.assign(col1=lst)
col1 col2
0 new1 test1
1 new2 test2
2 new3 test3
3 new4 test4
4 new5 test5
更一般化
这更通用。如果您不使用 Python 3.6 并且有 f 字符串,则可以使用 str.format
df.assign(col1=[f'new{i+1}' for i in range(len(df))])
# df.assign(col1=[*map('new{}'.format, range(1, len(df) + 1))])
col1 col2
0 new1 test1
1 new2 test2
2 new3 test3
3 new4 test4
4 new5 test5
使用itertools
如果你只想重复你得到的列表,我会使用 itertools
islice
和 cycle
from itertools import cycle, islice
df.assign(col1=[*islice(cycle(lst), len(df))])
col1 col2
0 new1 test1
1 new2 test2
2 new3 test3
3 new4 test4
4 new5 test5
关于python-3.x - 如何重命名列表中列中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54909624/