JSolomonCulp JSolomonCulp - 3 months ago 7
Python Question

Pandas Add Values of Column to Different Dataframe

So I have a dataframe, df1, that has 3 rows, A, B, and C as such:

A B C
Arizona 0 2.800000 5.600000
California 0 18.300000 36.600000
Colorado 0 2.666667 5.333333
Connecticut 0 0.933333 1.866667
Delaware 0 0.100000 0.200000
Florida 0 0.833333 1.666667
Georgia 0 0.000000 0.000000
Hawaii 0 1.000000 2.000000
Illinois 0 3.366667 6.733333
Indiana 0 0.000000 0.000000
Iowa 0 0.000000 0.000000


I then have another dataframe, df2, that has just one column, D:

D
Arizona 13
California 18
Colorado 5
Connecticut 15
Delaware 7
Florida 5
Georgia 13
Hawaii 3
Illinois 21
Indiana 2
Iowa 4


What I'd like to do is add the values of column D to all the columns in df1. By add I mean take the value of [Arizona, A] and add it to the value of [Arizona, D] not add column D as a new column. So far I tried using

df1 + df2 #returned all NaN
df1 + df2['D'] #Also returned all NaN
df1['A'] + df2['D'] #Returned a new dataframe with each as a separate column


I'm now not entirely sure where to go from here so I'd love some advice on how to solve this. It doesn't seem like it should be difficult and I'm probably missing something obvious but here I am.

Answer

you can use add() method:

In [22]: df1.add(df2.D, axis='index')
Out[22]:
                A          B          C
Arizona      13.0  15.800000  18.600000
California   18.0  36.300000  54.600000
Colorado      5.0   7.666667  10.333333
Connecticut  15.0  15.933333  16.866667
Delaware      7.0   7.100000   7.200000
Florida       5.0   5.833333   6.666667
Georgia      13.0  13.000000  13.000000
Hawaii        3.0   4.000000   5.000000
Illinois     21.0  24.366667  27.733333
Indiana       2.0   2.000000   2.000000
Iowa          4.0   4.000000   4.000000