Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting just a string element from a pandas dataframe

Tags:

python

list

names

Okay, so say I have a pandas dataframe x, and I'm interested in extracting a value from it:

> x.loc[bar==foo]['variable_im_interested_in']

Let's say that returns the following, of type pandas.core.series.Series:

24    Boss
Name: ep_wb_ph_brand, dtype: object

But all I want is the string 'Boss'. Wrapping the first line of code in str() doesn't help either, I just get:

'24    Boss\nName: ep_wb_ph_brand, dtype: object'

How do I just extract the string?

like image 460
Hillary Sanders Avatar asked Feb 26 '15 01:02

Hillary Sanders


People also ask

How do I extract a string from a DataFrame in Python?

The str. extract() function is used to extract capture groups in the regex pat as columns in a DataFrame. For each subject string in the Series, extract groups from the first match of regular expression pat.

How do you extract a single element from a DataFrame?

get_value() function is used to quickly retrieve the single value in the data frame at the passed column and index. The input to the function is the row label and the column label.


1 Answers

Code to get the last value of an array (run in a Jupyter notebook, noted with the >s):

> import pandas
> df = pandas.DataFrame(data=['a', 'b', 'c'], columns=['name'])
> df
    name
0   a
1   b
2   c
> df.tail(1)['name'].values[0]
'c'
like image 57
dfrankow Avatar answered Oct 12 '22 11:10

dfrankow