python-3.x - 使用同一数组重新分配多个列

标签 python-3.x pandas

我一直在为这个简单的事情伤透脑筋。我们可以使用 .loc 将单个值分配给多个列。但如何使用同一个数组分配多个列。

我可以做到这一点。假设我们有一个数据框 df,我希望用数组 arr 替换其中的一些列:

df=pd.DataFrame({'a':[random.randint(1,25) for i in range(5)],'b':[random.randint(1,25) for i in range(5)],'c':[random.randint(1,25) for i in range(5)]})
>>df
    a   b   c
0   14  8   5
1   10  25  9
2   14  14  8
3   10  6   7
4   4   18  2
arr = [i for i in range(5)]


#Suppose if I wish to replace columns `a` and `b` with array `arr`
df['a'],df['b']=[arr for j in range(2)]
Desired output:
    a   b   c
0   0   0   16
1   1   1   10
2   2   2   1
3   3   3   20
4   4   4   11

或者我也可以在循环赋值中执行此操作。但是有没有更有效的方法而不需要重复或循环呢?

最佳答案

让我们尝试一下 assign :

cols = ['a', 'b']
df.assign(**dict.fromkeys(cols, arr))

   a  b  c
0  0  0  5
1  1  1  9
2  2  2  8
3  3  3  7
4  4  4  2

关于python-3.x - 使用同一数组重新分配多个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65475162/

相关文章:

python-3.x - python asyncio 无法异步运行两个无限函数

python - 如何在 numpy 中将 int 值更改/重新映射到 str

python-3.x - 为什么 Qt 中的字体显得模糊或像素化?

python - 为什么 Python 的行为就像我的字典是一个列表?

python - Pandas :根据列中的条件测试替换记录

Python:将奇怪的字典转换为 Pandas - 数据框

python - 在 Python/Pandas 中什么时候调用 object.method 和 module.function?

python - 将月份添加到 Pandas 的日期时间列

python - Pandas 交叉表,但具有来自第三列聚合的值

python - 使用 Python 按比例计算所有权