Home > Enterprise >  I am having troubling indexing a dataframe
I am having troubling indexing a dataframe

Time:11-29

So I have a csv, and I am trying to load it into a dataframe via

df = pd.read_csv("watchlist.csv", sep='\s{2,}',)

It seems to work fine when I print(df)

Also, when I print columns, this is the output I get.

print(df.columns) #- OUTPUT:

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

The trouble I'm having, is that when I try to then go and access a column with something like

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

I get an attribute error:

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

Any assistance here would be appreicated

CodePudding user response:

 sep='\s{2,}' parameter will cause column list to become an object of type string, example:

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

 When you try to access a specific column math.floor(df.Debt) it returns

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

or maybe df["Debt"]

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

 To have access on specific columns of df by this way, use:

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

CodePudding user response:

The separator is not separating the csv correctly, try leaving it out and letting the csv reader use the default value of , instead.

  • Related