将新列元素显式添加到 Pandas DataFrame 中的现有行 (Python 2)

Add new column elements to explicitly to existing row in Pandas DataFrame (Python 2)

我正在尝试向行中添加列,如 Adding new column to existing DataFrame in Python pandas

I want to go from:
   a  b  c
A  1  2  3
B -1 -2 -3


   a  b  c  d  e  f  g
A  1  2  3  4  5  6  7
B -1 -2 -3 -4 -5 -6 -7

我已经为 columns/row 节点定义了我想要的值。我想明确地添加到具有给定索引的行以增加列数(例如 DF.ix["A"] = DF.ix["A"] + pd.Series([4,5,6,7],name="A",index=list("defg"))

下面的代码可以工作,但是如果不创建新的 DataFrame 并将它们连接起来,我该怎么做呢?我的真实价值是巨大的,如果可以的话,我想避免创建不必要的 DataFrame 对象。

#!/usr/bin/python
import pandas as pd

X = [[1,2,3],[-1,-2,-3]]

r_labels = ["A","B"]         
c_labels = ["a","b","c"]

DF = pd.DataFrame(X)
DF.index = r_labels
DF.columns = c_labels

#I want to add columns [d,e,f,g] to each row
row1 = [('d', 4), ('e', 5), ('f', 6), ('g', 7)]
row2 = [('d', -4), ('e', -5), ('f', -6), ('g', -7)]
DF_tmp = pd.DataFrame()
for r_label,row in zip(DF.index,[row1,row2]):
    SR_row = pd.Series([x[1] for x in row],name=r_label,index=[x[0] for x in row])
    DF_tmp = DF_tmp.append(SR_row)

DF = pd.concat([DF, DF_tmp], axis=1, join_axes=[DF.index])#, how='outer', on=DF_tmp.columns)            

如果您只想添加一些随机整数和一些新列,那么您可以这样做:

In [16]:
pd.concat([DF, pd.DataFrame(columns=list('defg'), data=np.random.randint(0, 4,(2,4)), index=DF.index)], axis=1)

Out[16]:
   a  b  c  d  e  f  g
A  1  2  3  0  2  1  3
B -1 -2 -3  3  0  3  3

编辑

列出所需行值的列表并构建 df 和 concat 它们:

In [20]:
new_A = [4,5,6,7]
new_B = [-4,-5,-6,-7]
l=[new_A,new_B]
l

Out[20]:
[[4, 5, 6, 7], [-4, -5, -6, -7]]

In [21]:
pd.concat([DF, pd.DataFrame(columns=list('defg'), data=l, index=DF.index)], axis=1)

Out[21]:
   a  b  c  d  e  f  g
A  1  2  3  4  5  6  7
B -1 -2 -3 -4 -5 -6 -7

既然你已经在循环了,为什么不直接:

In [1]: df = pd.DataFrame([[1,2,3],[-1,-2,-3]], columns=list('abc'), index=list('AB'))

In [2]: for c in 'defg':
            df[c] = np.random.rand(len(df))

In [3]: df
Out[3]: 
   a  b  c         d         e         f         g
A  1  2  3  0.173682  0.332771  0.151931  0.250421
B -1 -2 -3  0.916427  0.664965  0.961631  0.512067

编辑:

根据您的评论,您可以随时将其更改为:

In [2]: for c, data in zip('defg', (d_data, e_data, f_data, g_data):
            df[c] = pd.Series(data, index=df.index)

您还可以使用预先确定的值创建另一个 DataFrame DF2,并将 DF2 的列添加到原始 DataFrame DF

DF2 = pd.DataFrame(
    [[11,12,13,14],
    [15,16,17,18]], 
    columns = ('x', 'y', 'z', 'u'), index=['A', 'B'])
DF2
    x   y   z   u
A   11  12  13  14
B   15  16  17  18
DF[['d', 'e', 'f', 'g']] = DF2[['x', 'y', 'z', 'u']]
DF
a   b   c   d   e   f   g
A   1   2   3   11  12  13  14
B   -1  -2  -3  15  16  17  18