1

This should be obvious but I cannot make it work.

I have a pandas dataframe A with column and index names:

A = pd.DataFrame([[10, 20], [4, 5], [20, 30]], 
                 columns = ['col1', 'col2'], 
                 index = ['row1', 'row2', 'row3'])

      col1  col2
row1    10    20
row2     4     5
row3    20    30

Then I have another dataframe B with only one row (without name, so default 0) and same column names as A

B = pd.DataFrame([[100, 200]], 
                 columns = ['col1', 'col2'])
      col1  col2
0      100   200

I want to add A+B so I obtain a new dataframe C:

      col1  col2
row1   110   220
row2   104   205
row3   120   230

The most obvious thing would be to do:

 A + B

      col1  col2
row1   NaN   NaN
row2   NaN   NaN
row3   NaN   NaN
0      NaN   NaN

Then I tried

A.sum(B)

TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed

Am I missing something? numpy arrays will do the job super easily, what's wrong with dataframes?

I know the index names don't match, but I want to apply the vector B to all rows of A.

2 Answers 2

1

Use

In [4472]: A + B.iloc[0]
Out[4472]:
      col1  col2
row1   110   220
row2   104   205
row3   120   230
Sign up to request clarification or add additional context in comments.

Comments

1

You need create Series from B by selecting by loc or iloc and then use add:

df = A.add(B.iloc[0])
print (df)
      col1  col2
row1   110   220
row2   104   205
row3   120   230

Detail:

print (B.iloc[0])
col1    100
col2    200
Name: 0, dtype: int64

Or select by index name:

df = A.add(B.loc[0])

print (B.loc[0])
col1    100
col2    200
Name: 0, dtype: int64

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.