简体   繁体   中英

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).

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.

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.

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

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()现在可用并且比其他一些解决方案更干净

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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