0

I have a data file with thousands of bills. When I try to extract a single cell value I notice the type is <class 'numpy.ndarray'>. Is there a way to extract an element as a primitive value like float or int directly from the dataframe or series?

    import pandasql as ps
    import pandas as pd
    
    df = pd.read_csv(strFPath, sep='|', encoding='windows-1252')
    strQry = "SELECT SUM(BILLHOURS) AS 'BILLHOURS' FROM df"
    dfQry = ps.sqldf(strQry, globals())
    intHoursAll = float(dfQry.values[0].round(2))
Vu Nguyen
  • 52
  • 5
Jorge
  • 336
  • 1
  • 4
  • 15
  • It'd help to provide a [mre]. For specifics, see [How to make good reproducible pandas examples](/q/20109391/4518341). – wjandrea Jun 20 '23 at 02:22

2 Answers2

1

Yes, I think you can use iloc

For example, to extract the value of the first column in the first row (0,0),

write this.

value = df.iloc[0, 0]

(value type depends on the data type of the cell. For example, numeric data can be int or float.)

Or

value = df['your_column_name'].iloc[0]

(df['your_column_name'] return pandas' series with all the values in that column)

Additionally, if you want to return the <class 'numpy.ndarray'> type,

write this.

numpyArrayValues = df['column_name'].values

develover
  • 203
  • 2
  • 5
1

You can use squeeze to reduce a Series of one element to a scalar value:

>>> df
  OTHER  BILLHOURS
0     B          4
1     B          8
2     A          2
3     C          3
4     C          3
5     B          9
6     C          5
7     C          8
8     A          4
9     B          3

>>> ps.sqldf(strQry, globals()).squeeze()
49
Corralien
  • 109,409
  • 8
  • 28
  • 52