从Dataframe的最后一行中选择特定列的正确方法

时间:2017-09-10 14:36:33

标签: python pandas

我有一个数据框stock_pick并尝试设置某个列的最后一行,如

stock_pick.iloc[-1]["Regime"] = 0

这导致了

/home/prowler/analysis-toolkit/anaconda2/envs/py3.6/lib/python3.6/site-packages/pandas/core/indexing.py:179: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)

为最后一行中的特定列选择和分配值的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

您可以使用get_loc作为列的位置,并且可以使用DataFrame.iloc

stock_pick.iloc[-1, stock_pick.columns.get_loc("Regime")] = 0

另一种解决方案是按DataFrame.loc选择,并按[-1]按位置选择索引:

stock_pick.loc[stock_pick.index[-1], "Regime"] = 0