从 Pandas DataFrame 中采样一行后,如何获得一个单元格的值? [英] Once I sample a row from a pandas DataFrame, how can I get a value of one cell?
问题描述
我有一个 pandas
DataFrame 并且我已经成功地从中采样了一行,但问题之一是它只是返回另一个 DataFrame.我需要读取返回的行并获取该行特定元素的值.
I have a pandas
DataFrame and I've successfully sampled a row from it, but one of the problems is that it simply returns another DataFrame. I need to read the returned row and get the value of a particular element of that row.
我的 DataFrame
看起来像:
Date Open High Low Close Adj Close Volume
0 1993-01-29 43.968700 43.968700 43.750000 43.937500 26.836645 1003200
1 1993-02-01 43.968700 44.250000 43.968700 44.250000 27.027504 480500
2 1993-02-02 44.218700 44.375000 44.125000 44.343700 27.084740 201300
3 1993-02-03 44.406200 44.843700 44.375000 44.812500 27.371080 529400
4 1993-02-04 44.968700 45.093700 44.468700 45.000000 27.485609 531500
我可以对一行进行采样:
I'm able to sample a row with:
start_state = self.market_data.iloc[:-self._num_trading_days_in_episode].sample(1)
最终看起来像:
Date Open High Low Close Adj Close Volume
5299 2014-02-13 180.839996 183.199997 180.830002 183.009995 165.017517 100542200
现在我需要弄清楚如何从该行读取 Open
的值.
Now I need to figure out how to read the value of Open
from that row.
推荐答案
使用:
start_state = self.market_data.iloc[:-self._num_trading_days_in_episode].sample(1)
首先可以通过通过标签选择DataFrame.loc
获取第一个索引值:
First is possible select by labels by DataFrame.loc
with get first value of index:
open = start_state.loc[start_state.index[0], 'Open']
#faster alternative
#open = start_state.at[start_state.index[0], 'Open']
或者通过 DataFrame.iloc
和 Index.get_loc
:
pos = market_data.columns.get_loc('Open')
open = start_state.iloc[0, pos]
#faster alternative
#open = start_state.iat[0, pos]
或者通过索引在numpy数组中选择第一个值:
Or select in numpy array first value by indexing:
open = start_state['Open'].values[0]
#pandas 0.24+
#open = start_state['Open'].to_numpy()[0]
或 Series.item
用于将一项 Series
转换为标量:
open = start_state['Open'].item()
这篇关于从 Pandas DataFrame 中采样一行后,如何获得一个单元格的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!