Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - Extracting value to basic python float

Tags:

python

pandas

I'm trying to extract a cell from a pandas dataframe to a simple floating point number. I'm trying

prediction = pd.to_numeric(baseline.ix[(baseline['Weekday']==5) & (baseline['Hour'] == 8)]['SmsOut'])

However, this returns

128   -0.001405
Name: SmsOut, dtype: float64

I want it to just return a simle Python float: -0.001405 How can I do that?

like image 847
lte__ Avatar asked Feb 26 '17 16:02

lte__


People also ask

How do I extract a value from a pandas DataFrame in Python?

get_value() function is used to quickly retrieve the single value in the data frame at the passed column and index. The input to the function is the row label and the column label.

How do you convert a data object to float in Python?

Use pandas DataFrame. astype() function to convert column from string/int to float, you can apply this on a specific column or on an entire DataFrame. To cast the data type to 54-bit signed float, you can use numpy. float64 , numpy.


1 Answers

Output is Series with one value, so then is more possible solutions:

  • convert to numpy array by to_numpy and select first value by indexing
  • select by position by iloc or iat
prediction = pd.to_numeric(baseline.loc[(baseline['Weekday'] ==5 ) & 
                                        (baseline['Hour'] == 8), 'SmsOut'])

print (prediction.to_numpy()[0])

print (prediction.iloc[0])
print (prediction.iat[0])

Sample:

baseline = pd.DataFrame({'Weekday':[5,3], 
                         'Hour':[8,4], 
                         'SmsOut':[-0.001405,6]}, index=[128,130])
print (baseline)
     Hour    SmsOut  Weekday
128     8 -0.001405        5
130     4  6.000000        3

prediction = pd.to_numeric(baseline.loc[(baseline['Weekday'] ==5 ) & 
                                        (baseline['Hour'] == 8), 'SmsOut'])

print (prediction)
128   -0.001405
Name: SmsOut, dtype: float64

print (prediction.to_numpy()[0])
-0.001405
print (prediction.iloc[0])
-0.001405
print (prediction.iat[0])
-0.001405
like image 166
jezrael Avatar answered Sep 27 '22 21:09

jezrael