Python 如何从 Pandas DataFrame 获取值而不是索引和对象类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30787901/
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-08-19 08:59:01  来源:igfitidea点击:

How to get a value from a Pandas DataFrame and not the index and object type

pythonpandasdataframe

提问by Eduardo

Say I have the following DataFrame

假设我有以下 DataFrame

Letter    Number
A          1
B          2
C          3
D          4

Which can be obtained through the following code

可以通过以下代码获得

import pandas as pd

letters=pd.Series(('A', 'B', 'C', 'D'))
numbers=pd.Series((1, 2, 3, 4))
keys=('Letters', 'Numbers')
df=pd.concat((letters, numbers), axis=1, keys=keys)

Now I want to get the value C from the column Letters.

现在我想从字母列中获取值 C。

The command line

命令行

df[df.Letters=='C'].Letters

will return

将返回

2    C
Name: Letters, dtype: object

How can I get only the value C and not the whole two line output?

我怎样才能只得到值 C 而不是整个两行输出?

采纳答案by valkn0t

df[df.Letters=='C'].Letters.item()

This returns the first element in the Index/Series returned from that selection. In this case, the value is always the first element.

这将返回从该选择返回的索引/系列中的第一个元素。在这种情况下,该值始终是第一个元素。

EDIT:

编辑:

Or you can run a loc() and access the first element that way. This was shorter and is the way I have implemented it in the past.

或者您可以运行 loc() 并以这种方式访问​​第一个元素。这是更短的,是我过去实施它的方式。

回答by EdChum

Use the valuesattribute to return the values as a np array and then use [0]to get the first value:

使用该values属性将值作为 np 数组返回,然后用于[0]获取第一个值:

In [4]:
df.loc[df.Letters=='C','Letters'].values[0]

Out[4]:
'C'

EDIT

编辑

I personally prefer to access the columns using subscript operators:

我个人更喜欢使用下标运算符访问列:

df.loc[df['Letters'] == 'C', 'Letters'].values[0]

This avoids issues where the column names can have spaces or dashes -which mean that accessing using ..

这避免了列名可以有空格或破折号的问题-,这意味着使用..

回答by Lewis

import pandas as pd

dataset = pd.read_csv("data.csv")
values = list(x for x in dataset["column name"])

>>> values[0]
'item_0'

edit:

编辑:

actually, you can just index the dataset like any old array.

实际上,您可以像任何旧数组一样索引数据集。

import pandas as pd

dataset = pd.read_csv("data.csv")
first_value = dataset["column name"][0]

>>> print(first_value)
'item_0'