Python 从单行 Pandas DataFrame 中提取值

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

Extract value from single row of pandas DataFrame

pythonpandas

提问by mttk

I have a dataset in a relational database format (linked by ID's over various .csv files).

我有一个关系数据库格式的数据集(通过各种 .csv 文件的 ID 链接)。

I know that each data frame contains only one value of an ID, and I'd like to know the simplest way to extract values from that row.

我知道每个数据框只包含一个 ID 值,我想知道从该行中提取值的最简单方法。

What I'm doing now:

我现在在做什么:

# the group has only one element
purchase_group = purchase_groups.get_group(user_id)
price = list(purchase_group['Column_name'])[0]

The third row is bothering me as it seems ugly, however I'm not sure what is the workaround. The grouping (I guess) assumes that there might be multiple values and returns a <class 'pandas.core.frame.DataFrame'>object, while I'd like just a row returned.

第三行让我很困扰,因为它看起来很丑,但是我不确定解决方法是什么。分组(我猜)假设可能有多个值并返回一个<class 'pandas.core.frame.DataFrame'>对象,而我只想返回一行。

采纳答案by EdChum

If you want just the value and not a df/series then call valuesand index the first element [0]so just:

如果您只需要值而不是 df/series,则调用values并索引第一个元素,[0]因此只需:

price = purchase_group['Column_name'].values[0]

will work.

将工作。

回答by Yesh

If purchase_grouphas single row then doing purchase_group = purchase_group.squeeze()would make it into a series so you could simply call purchase_group['Column_name']to get your values

如果purchase_group有单行,那么这样做purchase_group = purchase_group.squeeze()会使其成为一个系列,这样您就可以简单地调用purchase_group['Column_name']以获取您的值