Extract value from single row of pandas DataFrame
Question:
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.
Answers:
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.
If purchase_group
has 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
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]
Late to the party here, but purchase_group['Column Name'].item()
is now available and is cleaner than some other solutions
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.
If purchase_group
has 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
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]
Late to the party here, but purchase_group['Column Name'].item()
is now available and is cleaner than some other solutions