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

hist2d using imported data from pandas: "too many values to unpack"

I’d like to plot a hist2d plot based on frequency using x and y data imported using iloc. However I keep getting the error:

ValueError: too many values to unpack

I’ve shown a picture of the type of figure I’m trying to produce along with my code:

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

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np


xls = pd.ExcelFile('test.xlsx')
df1 = pd.read_excel(xls, sheet_name='Sheet1', skiprows=1)

x = df1.iloc[[2]]
y = df1.iloc[[3]]

plt.figure(figsize = (10, 6), dpi = 80)
plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams.update({'font.size': 12})

CPT13 =plt.hist2d(x,y, bins=(50, 50), cmap=plt.cm.jet)
 
plt.show()

enter image description here

>Solution :

  • When iloc is given a list of index(es), it returns a 2D DataFrame:

    x = df1.iloc[[2]] # list indexer [2] returns 3rd row as 2D DataFrame
    y = df1.iloc[[3]]
    
  • But hist2d expects x and y each to be 1D arrays, which causes the error.

    x, y: array-like, shape (n,)


To extract the 3rd and 4th columns, use:

x = df1.iloc[:, 2] # colon indexer specifies all rows
y = df1.iloc[:, 3]

To extract the 3rd and 4th rows, use:

x = df1.iloc[2] # single brackets
y = df1.iloc[3]
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