如何从数据框的单元格中获取值?
问题描述:
我已经构建了一个从数据框中提取出一行的条件:
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']
但是,我得到一个包含一行和一列( ie 一个单元格)的数据框。这不是我需要的我需要一个值(一个浮点数)。如何在大熊猫中做到这一点?
But as a result I get a data frame that contains one row and one column (i.e. one cell). It is not what I need. I need one value (one float number). How can I do it in pandas?
答
如果您只有一行的DataFrame,则访问第一个(仅)作为使用 iloc
的系列,然后使用列名称的值:
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:
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