本文翻译自:How to get a value from a cell of a dataframe?
I have constructed a condition that extract exactly one row from my data frame: 我构造了一个条件,可以从我的数据帧中准确提取一行:
d2 = df[(df['l_ext']==l_ext) & (df['item']==item) & (df['wn']==wn) & (df['wd']==1)]
Now I would like to take a value from a particular column: 现在,我想从特定列中获取一个值:
val = d2['col_name']
But as a result I get a data frame that contains one row and one column ( ie one cell). 但是结果是我得到一个包含一行一列( 即一个单元格)的数据帧。 It is not what I need. 这不是我所需要的。 I need one value (one float number). 我需要一个值(一个浮点数)。 How can I do it in pandas? 我该怎么做在熊猫里?
#1楼
参考:https://stackoom.com/question/18C7q/如何从数据框的单元格获取值
#2楼
If you have a DataFrame with only one row, then access the first (only) row as a Series using iloc
, and then the value using the column name: 如果您的DataFrame仅包含一行,则使用iloc
作为系列访问第一(唯一)行,然后使用列名访问值:
In [3]: sub_df
Out[3]:
A B
2 -0.133653 -0.030854
In [4]: sub_df.iloc[0]
Out[4]:
A -0.133653
B -0.030854
Name: 2, dtype: float64
In [5]: sub_df.iloc[0]['A']
Out[5]: -0.13365288513107493
#3楼
These are fast access for scalars 这些是标量的快速访问
In [15]: df = pandas.DataFrame(numpy.random.randn(5,3),columns=list('ABC'))
In [16]: df
Out[16]:
A B C
0 -0.074172 -0.090626 0.038272
1 -0.128545 0.762088 -0.714816
2 0.201498 -0.734963 0.558397
3 1.563307 -1.186415 0.848246
4 0.205171 0.962514 0.037709
In [17]: df.iat[0,0]
Out[17]: -0.074171888537611502
In [18]: df.at[0,'A']
Out[18]: -0.074171888537611502
#4楼
It looks like changes after pandas 10.1/13.1 熊猫10.1 / 13.1之后看起来像变化
I upgraded from 10.1 to 13.1, before iloc is not available. 在iloc不可用之前,我从10.1升级到13.1。
Now with 13.1, iloc[0]['label']
gets a single value array rather than a scalar. 现在使用13.1, iloc[0]['label']
获得单个值数组,而不是标量。
Like this: 像这样:
lastprice=stock.iloc[-1]['Close']
Output: 输出:
date
2014-02-26 118.2
name:Close, dtype: float64
#5楼
For pandas 0.10, where iloc
is unavalable, filter a DF
and get the first row data for the column VALUE
: 对于iloc
不可使用的0.10熊猫,过滤DF
并获取VALUE
列的第一行数据:
df_filt = df[df['C1'] == C1val & df['C2'] == C2val]
result = df_filt.get_value(df_filt.index[0],'VALUE')
if there is more then 1 row filtered, obtain the first row value. 如果过滤的行数超过1,则获取第一行的值。 There will be an exception if the filter result in empty data frame. 如果过滤器导致数据帧为空,则会出现异常。
#6楼
Not sure if this is a good practice, but I noticed I can also get just the value by casting the series as float
. 不知道这是否是一个好习惯,但是我注意到我也可以通过将序列强制转换为float
来获得值。
eg 例如
rate
3 0.042679 3 0.042679
Name: Unemployment_rate, dtype: float64 名称:Unemployment_rate,dtype:float64
float(rate)
0.0426789 0.0426789