【问题标题】:I am having troubling indexing a dataframe我在索引数据框时遇到了麻烦
【发布时间】:2022-01-05 22:12:54
【问题描述】:

所以我有一个 csv,我正在尝试通过

将它加载到数据框中
df = pd.read_csv("watchlist.csv", sep='\s{2,}',)

当我print(df)时它似乎工作正常

另外,当我打印列时,这是我得到的输出。

print(df.columns) #- OUTPUT:

Index([',Name,Growth,Recommendation,CurrentRatio,TotalCash,Debt,Revenue,PercentageSharesOut,PercentageInstitutions,PercentageInsiders,PricetoBook,ShortRatio,RegularMarketPrice'], dtype='object')

我遇到的麻烦是,当我尝试去访问一个类似的列时

med_debt = math.floor(df.Debt), or even 
print(df.Debt)

我得到一个属性错误:

AttributeError: 'DataFrame' object has no attribute 'Debt'

如有任何帮助,我们将不胜感激

【问题讨论】:

  • 您的 DataFrame 没有名为 Debt 的列。它也没有名称为 NameGrowth 等的列。它有 one 列,其名称为 ,Name,Growth,Recommendation,CurrentRatio,TotalCash,Debt,Revenue,PercentageSharesOut,PercentageInstitutions,PercentageInsiders,PricetoBook,ShortRatio,RegularMarketPrice。这是因为在读取 CSV 文件时,\s{2,} 是用于 sep 的错误值。我猜你的意思是\s{2},
  • 如果你只是做print(df) 来判断你的列的输出,输出看起来像什么,看起来只有一列只是列名的字符串组合。
  • @KarlKnechtel 我想我添加它是为了尝试解决不同的问题,我会删除它,谢谢

标签: python pandas dataframe csv


【解决方案1】:

分隔符未正确分隔 csv,请尝试将其保留并让 csv 阅读器使用默认值 ,

【讨论】:

    【解决方案2】:

     sep='\s{2,}' 参数将导致 column list 变为 type stringobject,例如:

    >>> df = pd.read_csv("weather", sep='\s{2,}')
    >>> df.columns
    Index(['Date/Time,Temp (C),Dew Point Temp (C),Rel Hum (%),Wind Spd (km/h),
    Visibility (km),Stn Press (kPa),Weather'], dtype='object')
    >>> df.index
    RangeIndex(start=0, stop=8784, step=1)
    

     当您尝试访问特定列 math.floor(df.Debt) 时,它会返回

    AttributeError: 'DataFrame' object has no attribute 'Debt'

    或者df["Debt"]

    raise KeyError(key) from err
    (KeyError: 'Debt')
    

     要通过这种方式访问​​df 的特定列,请使用:

    df = pd.read_csv("watchlist.csv")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-06
      • 2013-11-11
      • 2011-08-28
      • 2017-08-25
      • 2016-06-29
      • 2013-01-06
      • 1970-01-01
      相关资源
      最近更新 更多