Python Forum
pandas dataframe substracting columns: key error - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: pandas dataframe substracting columns: key error (/thread-2166.html)



pandas dataframe substracting columns: key error - metalray - Feb-23-2017

Hi Pandas Experts,

I got a dataframe that has a country and its GDP for the year 2015 up to 2006

    newfour = newtwo[(newtwo['2015']-newtwo['2006'])]
When I try to substract 2015 from 2006 and ingone the rest I read the error:

KeyError: '[  4.80566748e+12   1.75626949e+12   1.73021626e+11   2.46702696e+11\n   2.30356251e+11   2.28139911e+11   3.52665152e+11   1.10131180e+12\n   1.53345695e+11   3.25560528e+11  -1.52854060e+11   4.99867550e+09\n              nan   2.79311766e+11   4.74343726e+11] not in index'

It seems the GDP values are not an/in index but I wonder why that is required?
Why does a column need to be an index to be subtracted from another?
Many thanks for any explanations


RE: pandas dataframe substracting columns: key error - zivoni - Feb-23-2017

Well, I am not entirely sure what do you want to achieve, but if you just need to count difference of two columns of pandas' dataframe,  then subtract them.

There is no need for your outer newtwo[...] selection , you are trying to use your computed differences as a keys and that wont work.

Output:
In [1]: import pandas as pd In [2]: newtwo = pd.DataFrame({'astate':['first', 'second'], 'gdp2010':[113.2, 341.1], 'gdp2015':[233.1, 417.1]}) In [3]: newtwo Out[3]:    astate  gdp2010  gdp2015 0   first    113.2    233.1 1  second    341.1    417.1 In [4]: newfour = newtwo['gdp2015'] - newtwo['gdp2010'] In [5]: newfour Out[5]: 0    119.9 1     76.0 dtype: float64 In [6]: newtwo[(newtwo['gdp2010'] - newtwo['gdp2015'])]    # same as newtwo[[-119.9, -76.0]] and that doesn't make sense ... ... KeyError: '[-119.9  -76. ] not in index'
You can find a nice short introduction to pandas on offical pandas page.


RE: pandas dataframe substracting columns: key error - metalray - Feb-24-2017

(Feb-23-2017, 01:41 PM)zivoni Wrote: There is no need for your outer newtwo[...] selection , you are trying to use your computed differences as a keys and that wont work.

I see. That was it! I still get confused with this key and index thing.