How to divide lines by lines of two different df and store in a third?

Asked

Viewed 34 times

0

inserir a descrição da imagem aqui inserir a descrição da imagem aqui

I try to divide using the methods div and divide and when assigning in a new df all values are as Nan

  • What code did you run to get Nan as a result? It’s hard to reproduce the error without knowing exactly what was done. It was something like df_2014['2014 [YR2014]'].div(df_2010['2010 [YR2010]'])?

  • Exactly that.

1 answer

1

If you specify the columns you want to split (even if each dataframe has only one column), just use the operator / ). The result is a Pandas.Series, which can be used as a column in a dataframe:

In [24]: df1 = pd.DataFrame({"2014": {"Albania": 5716.853}})                                                            

In [25]: df2 = pd.DataFrame({"2000": {"Albania": 3021.608}})                                                            

In [26]: df1["2014"] / df2["2000"]                                                                                      
Out[26]: 
Albania    1.89199
dtype: float64

Better than having each column in a separate dataframe is to put it all together:

df1 = pd.DataFrame({"2014": {"Albania": 5716.853}})
df2 = pd.DataFrame({"2000": {"Albania": 3021.608}})
ratio = df1["2014"] / df2["2000"]
ratio.name = "Taxa de crescimento"
final = pd.concat((df1, df2, result), axis=1)

Representation of the final DF:

In [37]: final                                                                                                          
Out[37]: 
             2014      2000  Taxa de crescimento
Albania  5716.853  3021.608              1.89199

Browser other questions tagged

You are not signed in. Login or sign up in order to post.