简体   繁体   English

从单行 pandas DataFrame 中提取值

[英]Extract value from single row of pandas DataFrame

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'>对象,而我只想返回一行。

If you want just the value and not a df/series then call values and index the first element [0] so just:如果您只想要值而不是 df/series,则调用values并索引第一个元素[0] ,只需:

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

will work.将工作。

如果purchase_group有单行,那么做purchase_group = purchase_group.squeeze()会将其变成一个系列,因此您可以简单地调用purchase_group['Column_name']来获取您的值

This method is intuitive;这种方法很直观; for example to get the first row (list from a list of lists) of values from the dataframe:例如,从数据框中获取值的第一行(列表列表中的列表):

np.array(df)[0]

在这里聚会迟到了,但是purchase_group['Column Name'].item()现在可用并且比其他一些解决方案更干净

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM