如何为 pandas 数据框中的多个不存在的列分配值? [英] How to assign values to multiple non existing columns in a pandas dataframe?
本文介绍了如何为 pandas 数据框中的多个不存在的列分配值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我要做的是将列添加到数据框,并用单个值填充它们(分别为所有行).
So what I want to do is to add columns to a dataframe and fill them (all rows respectively) with a single value.
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"
我确实知道分配功能以及如果一次只添加一列我将如何解决此问题.我只是想知道是否有一种干净简单的方法可以对多个新列执行此操作,因为我找不到一个.
I do know about the assign-functionality and how I would tackle this issue if I only were to add one column at once. I just want to know whether there is a clean and simple way to do this with multiple new columns as I was not able to find one.
推荐答案
为我工作:
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
这篇关于如何为 pandas 数据框中的多个不存在的列分配值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文