Python 如果索引是时间戳,如何从熊猫列表

Python 如果索引是时间戳,如何从熊猫列表,python,pandas,list,dataframe,Python,Pandas,List,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 如果我这样写代码 b=[] b.append((df.iloc[2]-df.iloc[1])/(df.iloc[1])) print(b) 输出为 [Ordered Items 0.106969 dtyp

这是我的数据框

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
如果我这样写代码

b=[]

b.append((df.iloc[2]-df.iloc[1])/(df.iloc[1]))

print(b)
输出为

[Ordered Items    0.106969
dtype: float64]
我只想要像
0.106969
这样的输出


我该怎么做呢?

如果您只想从输出中获取值,可以使用返回numpy数组的
df.values
。如果您需要该numpy数组中的列表,那么可以使用
np\u array.tolist

所以

b=((df.iloc[2]-df.iloc[1])/(df.iloc[1])。值#返回numpy数组
b、 tolist#返回python列表

您可以执行以下操作

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]

希望有帮助。

您正在使用
系列
,这就是您得到此结果的原因。 您的
iloc
返回1个元素的
Series
,算术运算符也返回Series。 如果要获取标量值,只需使用
my_series[0]

以你为例:

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


查看
DataFrame.to\u字符串(index\u names=False)