Home > Software engineering >  hist2d using imported data from pandas: "too many values to unpack"
hist2d using imported data from pandas: "too many values to unpack"

Time:12-13

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:

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

CodePudding user response:

  • 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]
  • Related