I'm trying to add columns to a row like in 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
I have defined values that I want for the columns/row nodes. I want to explicitly add to a row with a given index to increase the number of columns (e.g. DF.ix["A"] = DF.ix["A"] + pd.Series([4,5,6,7],name="A",index=list("defg"))
The code below works, but how can I do this WITHOUT creating a new DataFrame and concatenating them? My real values are HUGE and I'd like to avoid creating an unncecessary DataFrame object if I can.
#!/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)