Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Plotting values over time with Pandas Dataframe

I’m looking to gather datapoints from each country for percentage and time from this Pandas dataframe. Pandas Dataframe

By using the pandas.iloc function I’ve been able to isolate each country’s data

SIPRI_share_GDP.iloc[0]

Which outputs:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Country    Algeria
1949          0.0%
1950          0.0%
1951          0.0%
1952          0.0%
            ...   
2015          6.3%
2016          6.4%
2017          5.9%
2018          5.5%
2019          6.0%

When I try to separate this output into two arrays of variables:

date_Algeria, GDP_pct_Algeria = SIPRI_share_GDP.iloc[0]

I get the error

ValueError: too many values to unpack (expected 2)

I don’t quite understand this error, as I thought the output was two arrays.

Would anyone be able to tell me where I am going wrong? Any help on how to properly separate the data into percent and time arrays?

Thank you!

>Solution :

What’s going on here is that Python sees this as a single object, a Pandas Series (pandas.core.series.Series). When you try to perform multiple assignment, it thinks you’re trying to assign each value from the series to a variable and finds that there aren’t enough variables to use.

You can access just the index (the part with the years) by using SIPRI_share_GDP.index, and just the values by using SIPRI_share_GDP.iloc[0].values, so your updated code would look like this:

date_Algeria, GDP_pct_Algeria = SIPRI_share_GDP.index, SIPRI_share_GDP.iloc[0].values

However, depending on the plotting package you’re using, you may not even need to separate them out. By default, some plotting packages will assume that the index of the Series is the desired x-values. Pandas has built-in integration with Matplotlib, so you can even just use:

SIPRI_share_GDP.iloc[0].plot()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading