从 Pandas DataFrame 行获取单元格值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47917460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:56:00  来源:igfitidea点击:

Get cell value from a pandas DataFrame row

pythonpandas

提问by Tony Piazza

I am new to pandas and have what I think should be a simple question. I have a simple DataFrame and I need to be able to get the value of a specific cell. Here is a sample of my DataFrame:

我是Pandas的新手,我认为应该是一个简单的问题。我有一个简单的 DataFrame,我需要能够获取特定单元格的值。这是我的 DataFrame 示例:

>>> airports.sample(5)
     iata               name        city state country
2144  M15       Perry County      Linden    TN     USA
2391  N69         Stormville  Stormville    NY     USA
861   ARA  Acadiana Regional  New Iberia    LA     USA
2596  PDX      Portland Intl    Portland    OR     USA
3238  VES       Darke County  Versailles    OH     USA

As an example of what I am trying to do, I need to get the value of the namecolumn for the row where the iatacolumn == 'PDX'. I can use the following syntax to retrieve the row I want:

作为我想要做的一个例子,我需要获取iata列 == 'PDX'所在行的名称列的值。我可以使用以下语法来检索我想要的行:

>>> airports[airports.iata == 'PDX'].name
2596    Portland Intl
Name: name, dtype: object

The question is now, how do I retrieve the valueof the name cell for this row?

现在的问题是,如何检索该行的名称单元格的

Thanks in advance for your help.

在此先感谢您的帮助。

-Tony

-托尼

回答by Bharath

.locreturns series when you do boolean indexing because there are chances that you have multiple match cases.

.loc当您进行布尔索引时返回系列,因为您可能有多个匹配案例。

df.loc[df.iata == 'PDX','name']

2596    Portland Intl
Name: name, dtype: object

If you want only the value then convert it to list and then access according to the index

如果您只想要该值,则将其转换为列表,然后根据索引进行访问

df.loc[df.iata == 'PDX','name'].tolist()[0]

Or access based on the index in values i.e

或基于值中的索引进行访问,即

df.loc[df.iata == 'PDX','name'].values[0]