python-3.x - 如何重命名列表中列中的值?

标签 python-3.x pandas

我有一个看起来像这样的 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 islicecycle

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/

相关文章:

python - 值错误: cannot use sparse input in 'SVC' trained on dense data

python - 删除列表中前 N 个元素的最有效方法?

Python Azure 队列,出现错误

python - 在数据框数据上调用函数

python - 如何通过for循环和def函数替换列值?

python - 更改 Pandas 中的列类型

python-3.x - 如果 set 大于 len(x),则 pandas 在重复行中拆分集合列

python - 检查单词是否在元组列表中

python - 如何让 virtualenv 在 mac 上的 python3 上工作

python - 根据 pandas 中的条件创建更多行