gpt4 book ai didi

python - 如何为 Pandas 数据框中的多个不存在的列赋值?

转载 作者:太空狗 更新时间:2023-10-30 00:42:39 24 4
gpt4 key购买 nike

所以我想做的是将列添加到数据框并用单个值填充它们(分别为所有行)。

import pandas as pd
import numpy as np

df = pd.DataFrame(np.array([[1,2],[3,4]]), columns = ["A","B"])
arr = np.array([7,8])

# this is what I would like to do
df[["C","D"]] = arr

# and this is what I want to achieve
# A B C D
# 0 1 2 7 8
# 1 3 4 7 8
# but it yields an "KeyError" sadly
# KeyError: "['C' 'D'] not in index"

我确实知道分配功能以及如果我一次只添加一列我将如何解决这个问题。我只是想知道是否有一种干净简单的方法来使用多个新列来执行此操作,因为我找不到一个。

最佳答案

对我来说工作:

df[["C","D"]] = pd.DataFrame([arr], index=df.index)

join :

df = df.join(pd.DataFrame([arr], columns=['C','D'], index=df.index))

assign :

df = df.assign(**pd.Series(arr, index=['C','D']))

print (df)
A B C D
0 1 2 7 8
1 3 4 7 8

关于python - 如何为 Pandas 数据框中的多个不存在的列赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49051969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com