[英]Access last item of list
这真是令人尴尬,但我不明白为什么list[-1]
方法不返回列表中的最后一项。
这是系列:
[df1['Close'] / highest(df1['Close'],20) > 1]
Output如下:
[2415 False
2416 False
2417 False
2418 False
2419 False
...
5614 False
5615 False
5616 False
5617 False
5618 False
Name: Close, Length: 3204, dtype: bool]
现在我尝试通过以下方式访问最后一个元素:
[df1['Close'] / highest(df1['Close'],20) > 1][-1]
它仍然抛出与上面相同的 output。 我一定做错了什么。
我可以将其转换为一个系列并且它有效。
(df1['Close'] / highest(df1['Close'],20) > 1).iloc[-1:]
但这不是我想要使用它的方式。
您的代码在列表中返回pandas.Series 。 因此,当您访问[-1]
时,您将在列表中获得 pandas 系列。 您可以通过调用.values[-1]
访问 pandas.Series 的最后一个值。
像这样:
[0]
访问列表中的 pandas 系列.values[-1]
访问系列的最后一个值[df1['Close'] / highest(df1['Close'],20) > 1][0].values[-1]
False
[df1['Close'] / highest(df1['Close'],20) > 1]
此代码仅将所有内容作为list
中的一个元素返回。 所以, [-1]
会返回一个完整的东西。
尝试.iloc
而不将series
放入list
:
(df1['Close'] / highest(df1['Close'],20) > 1).iloc[-1]
使用方括号 ( [
]
) 将构造一个列表。 请改用括号:
(df1['Close'] / highest(df1['Close'],20) > 1)[-1]
或者使用函数:
df1['Close'].div(highest(df1['Close'], 20)).gt(1)[-1]
或者最好的是iloc
:
df1['Close'].div(highest(df1['Close'], 20)).gt(1).iloc[-1]
您还可以使用some_list[len(some_list)-1]
给出最后一个元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.