Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas - Take first value from column and put into a variable

Tags:

python

pandas

I have a DataFrame (df) that I get from an input (uses SQL to get data):

| Grant      | Summary     |
|:-----------|------------:|
| J0014/1    |  foobar     | 

It will only ever be one row.

How do I get the value from the Summary column into a variable to use later i.e. I dont want the column header, I want a situation where this happens:

aVar = foobar

Apologies if this is a simple question, but for some reason my brain isnt working this morning. Thank you

like image 398
ScoutEU Avatar asked Jul 31 '26 09:07

ScoutEU


1 Answers

Simpliest is select first value of column by Series.iat:

aVar = df['Summary'].iat[0]

Solutions with iloc, loc, because ix indexer is deprecated:

iloc is for select by positions, so need position of column Summary by get_loc:

aVar = df.iloc[0, df.columns.get_loc('Summary')]

loc select by names, so use:

#default index - first value is 0
aVar = df.loc[0, 'Summary']
#general solution with unique index - seelct first value by `[0]`
aVar = df.loc[df.index[0], 'Summary']
like image 125
jezrael Avatar answered Aug 02 '26 23:08

jezrael