Pandas Dataframe 显示ValueError和类

h7appiyu  于 2023-03-06  发布在  其他
关注(0)|答案(1)|浏览(164)

我正在尝试在一个名为CaptainAmerica的类中创建一个Dataframe。我正在尝试使用finalStats变量实现值。我一直期待输出,直到遇到此错误:
raise ValueError("If using all scalar values, you must pass an index") ValueError: If using all scalar values, you must pass an index
代码:

`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()`

我目前使用的是https://trinket.io/embed/python3/a5bd54189b在线编译器。谢谢。

db2dz4w8

db2dz4w81#

使用pd.Series代替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()

输出:

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

您还可以执行以下操作:

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

# Output
                Damage  Health  Speed  Stamina  Powers
CaptainAmerica      80      95     95       95       0

相关问题