gpt4 book ai didi

python - 使用 [-1] 获取列的最后一行?

转载 作者:行者123 更新时间:2023-12-04 10:06:37 25 4
gpt4 key购买 nike

我到处都是这样的代码,似乎工作正常。

df['FAST_MA'] = df['close'].rolling(5).mean()
lfma = df['FAST_MA'][-1]

但是在其他地方,当我尝试时会出现一般错误:
  ERROR - error from callback <function on_message at 0x12619cc20>: -1.0
File "/usr/local/lib/python3.7/site-packages/websocket/_app.py", line 346, in _callback
callback(self, *args)
File "file.py", line 177, in calculate
lfma = df['FAST_MA'][-1]
File "/usr/local/lib/python3.7/site-packages/pandas/core/series.py", line 868, in __getitem__
result = self.index.get_value(self, key)
File "/usr/local/lib/python3.7/site-packages/pandas/core/indexes/numeric.py", line 375, in get_value
loc = self.get_loc(k)
File "/usr/local/lib/python3.7/site-packages/pandas/core/indexes/numeric.py", line 436, in get_loc
tolerance=tolerance)
File "/usr/local/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 2659, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 382, in pandas._libs.hashtable.Float64HashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 388, in pandas._libs.hashtable.Float64HashTable.get_item

然后我必须做这样的事情。
# df['FAST_MA'] = df['close'].rolling(5).mean()
lfma = df['FAST_MA'].iloc[-1]

有什么区别,怎么可能 df['FAST_MA'][-1]在意想不到的情况下休息?

最佳答案

我尝试模拟问题,选择 DatetimeIndex两种方式都很好:

df = pd.DataFrame({
'close': list(range(4))}, index=pd.date_range('2019-10-01', periods=4))
print (df)

df['FAST_MA'] = df['close'].rolling(2).mean()
print (df)
close FAST_MA
2019-10-01 0 NaN
2019-10-02 1 0.5
2019-10-03 2 1.5
2019-10-04 3 2.5

print (df['FAST_MA'][-1])
2.5
print (df['FAST_MA'].iloc[-1])
2.5

但对于默认 RangeIndex :
d = {'close': [1, 2, 3], 'col2': [3, 4, 5]}
df=pd.DataFrame(data=d)

df['FAST_MA'] = df['close'].rolling(2).mean()
print (df)

print (df['FAST_MA'].iloc[-1])
close col2 FAST_MA
0 1 3 NaN
1 2 4 1.5
2 3 5 2.5

print (df['FAST_MA'][-1])
KeyError: -1

这个错误意味着 Pandas 正在寻找索引值 -1而不是最后一个位置,因为不存在提高 KeyError .

最通用的解决方案是使用方法 Series.iloc Series.iat .

另外如果想在 DataFrame中选择也可以使用 DataFrame.iat , DataFrame.iloc :
df.iat[-1, df.columns.get_loc('FAST_MA')]
df.iloc[-1, df.columns.get_loc('FAST_MA')]

关于python - 使用 [-1] 获取列的最后一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61554367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com