Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to select a specific column from the last row of a Dataframe

Tags:

python

pandas

I have a dataframe stock_pick and trying to set last row of certain column like

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

This results in the ,

/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)

What is the correct way to pick and assign a value to a specific column in the last row?

like image 362
user2663139 Avatar asked Sep 10 '17 14:09

user2663139


People also ask

How do I select a specific column in a DataFrame?

If you have a DataFrame and would like to access or select a specific few rows/columns from that DataFrame, you can use square brackets or other advanced methods such as loc and iloc .

How do you select the last column in a DataFrame?

Use iloc[] to select last column of pandas dataframe. Use [] to select last column of pandas dataframe. Use tail() to select last column of pandas dataframe. Get last column of pandas dataframe as list on python.


1 Answers

You can use get_loc for position of column and thn is posssible use DataFrame.iloc:

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

Another solution is select by DataFrame.loc and select index by position by [-1]:

stock_pick.loc[stock_pick.index[-1], "Regime"] = 0
like image 67
jezrael Avatar answered Oct 23 '22 11:10

jezrael