Pandas dataframe showing ValueError with class

Question:

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:

`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.

Asked By: Ray953

||

Answers:

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
Answered By: Corralien
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.