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

Pandas dataframe showing ValueError with class

I am trying to make a Dataframe inside a class called CaptainAmerica. I am trying to implement the values using the finalStats variable. I was expecting output until I ran into this error:

raise ValueError("If using all scalar values, you must pass an index") ValueError: If using all scalar values, you must pass an index

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

class CaptainAmerica:
    def __init__(self,damage,health,speed,stamina,superpowers):
      self.damage = damage
      self.health = health
      self.speed = speed
      self.stamina = stamina
      self.superpowers = superpowers
      
    def statsOfCap(self):
        df = {
          "Damage":self.damage,
          "Health":self.health,
          "Speed": self.speed,
          "Stamina": self.stamina,
          "Powers": self.superpowers
        }
        result = pd.DataFrame(df)
        print(result)


finalStats = CaptainAmerica(80,95,95,95,0)

finalStats.statsOfCap()`

I am currently using https://trinket.io/embed/python3/a5bd54189b online compiler.
Thank you.

>Solution :

Use pd.Series instead of a pd.DataFrame:

import pandas as pd

class CaptainAmerica:
    def __init__(self,damage,health,speed,stamina,superpowers):
      self.damage = damage
      self.health = health
      self.speed = speed
      self.stamina = stamina
      self.superpowers = superpowers
      
    def statsOfCap(self):
        df = {
          "Damage":self.damage,
          "Health":self.health,
          "Speed": self.speed,
          "Stamina": self.stamina,
          "Powers": self.superpowers
        }
        result = pd.Series(df)  # <- HERE
        print(result)


finalStats = CaptainAmerica(80,95,95,95,0)

finalStats.statsOfCap()

Output:

Damage     80
Health     95
Speed      95
Stamina    95
Powers      0
dtype: int64

You can also do:

result = pd.Series(df).to_frame(self.__class__.__qualname__).T

# Output
                Damage  Health  Speed  Stamina  Powers
CaptainAmerica      80      95     95       95       0
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