Reputation: 350
Here is my dataframe
ord_datetime
2019-05-01 22.483871
2019-05-02 27.228070
2019-05-03 30.140625
2019-05-04 32.581633
2019-05-05 30.259259
if i do code like this
b=[]
b.append((df.iloc[2]-df.iloc[1])/(df.iloc[1]))
print(b)
output is
[Ordered Items 0.106969
dtype: float64]
I want an output like 0.106969
only
How can i do that?
Upvotes: 2
Views: 352
Reputation: 2729
You can do something like the following
import pandas as pd
data = {
"ord_datetime": ["2019-05-01","2019-05-02","2019-05-03","2019-05-04","2019-05-05"],
"value": [22.483871,27.228070,30.140625,32.581633,30.259259]
}
df = pd.DataFrame(data=data)
res = [ (df.iloc[ridx + 1, 1] - df.iloc[ ridx, 1]) / (df.iloc[ridx, 1]) for ridx in range(0, df.shape[0]-1) ]
res # [0.2110045463256749, 0.10696883767376833, 0.08098730533955406, -0.0712786249848188]
Hope it helps.
Upvotes: 1
Reputation: 6903
You are working with Series
here, which is why you get this result.
Your iloc
returns a Series
of 1 element, and the arithmetic operators also return series.
If you want to get the scalar value, you can simply use my_series[0]
.
So for your example:
data = {datetime(2019, 5, 1): 22.483871, datetime(2019, 5, 2): 27.228070,
datetime(2019, 5, 3): 30.140625, datetime(2019, 5, 4): 32.581633,
datetime(2019, 5, 5): 30.259259}
df = pd.DataFrame.from_dict(data, orient="index")
series_result = (df.iloc[2] - df.iloc[1]) / df.iloc[1]
scalar_result = series_result[0]
# you can append the result to your list if you want
Upvotes: 1
Reputation: 53
If you want to just get the values from the output you can use df.values
which returns a numpy array. If you want a list from that numpy array you can then use np_array.tolist
.
So
b = ((df.iloc[2]-df.iloc[1])/(df.iloc[1])).values #returns numpy array
b.tolist # returns python list
Upvotes: 0