0

I have a pandas data frame that contains one row. I know what the column names are in this row. I would like to pull the value (just the value, not the type, or other metadata) from each cell in this row. How do I do this? I am using Python 3.

I have tried the following, but it always fails, because you can't use a column.

print(data_frame.head().values['ColumnName'])

So then I tried this, which gives me the value of ColumnName, but then crashes.

print(data_frame.iloc[0]['ColumnName'])

File "/usr/local/lib/python3.8/dist-packages/pandas/core/indexing.py", line 895, in getitem return self._getitem_axis(maybe_callable, axis=axis) File "/usr/local/lib/python3.8/dist-packages/pandas/core/indexing.py", line 1501, in _getitem_axis self._validate_integer(key, axis) File "/usr/local/lib/python3.8/dist-packages/pandas/core/indexing.py", line 1444, in _validate_integer raise IndexError("single positional indexer is out-of-bounds") IndexError: single positional indexer is out-of-bounds

I can get it to work if I loop through it, but I don't need or want this since I only have one row.

for x in data_frame.itertuples(index=False):
     print(x.ColumnName1)
     print(x.ColumnName2)

I also was able to get something to give me the value along with a bunch of other metadata, but unfortunately I can't recall what code I used to get that.

All I want to do is something like this and get the value of ColumnName.

data_frame[0]['ColumnName']

Is this possible?

Edit Here is the code. It calls a stored procedure in a SQL database.

    query = "EXEC p_get_data @id = '{0}'".format(id)
connection_string = get_connection_string()
engine = sqlalchemy.create_engine(connection_string)
data_frame = pd.read_sql_query(query, engine)
data_frame.reset_index(inplace=True)

#print(data_frame.loc[0]['ColumnName1'])
#print(data_frame.loc[0, 'ColumnName1'])
#print(data_frame['ColumnName1'].values[0])
#print(data_frame['ColumnName1'].iloc[0])
#print(data_frame.iat[0, data_frame.columns.get_loc('ColumnName1')])
print(data_frame['ColumnName1'][0] )

The stored procedure

ALTER PROCEDURE [dbo].[p_get_data]
    @id varchar(200)
AS
    SELECT A.ColumnName1, E.ColumnName2 
    FROM E (NOLOCK)
    INNER JOIN A (NOLOCK) ON E.PrimaryKey = A.PrimaryKey
    WHERE Id = @id
      AND A.Type = 'test' 

The data looks like this: (ColumnName1 is an integer, ColumnName2 is a varchar

ColumnName1     ColumnName2
---------------------------
1               ABCDE1234
1
  • try this: data_frame['ColumnName'][0] Commented Apr 29, 2021 at 20:16

2 Answers 2

1

If it's single row, You should be fine using something like this:

>>> data_frame['colName'].values[0]
Out[8]: 1

Or,

>>> data_frame['colName'].iloc[0]
Out[9]: 1

Or,

>>> data_frame.iloc[0, data_frame.columns.get_loc('colName')]
Out[11]: 1

Or,

>>> data_frame.iat[0, data_frame.columns.get_loc('colName')]
Out[12]: 1

Or,

>>> data_frame.loc[0, 'colName']
Out[13]: 1
Sign up to request clarification or add additional context in comments.

5 Comments

All of these fail with 'IndexError: single positional indexer is out-of-bounds; type errors.
I have even included the output, all of them seem to be working fine... Try adding your data to the question
The reason could be the index as well, try resetting your index. data_frame.reset_index(inplace=True)
Just edited the question. I got the same error when using the reset_index.
The error I was getting was because I was looping through some values and calling the stored procedure multiple times.. One of those times was returning a 0 length data frame. That was the source of the index out of range. Thanks for your help.
0

Toy example

Lets say you have following DataFrame:

In [1]: import pandas as pd
In [5]: df = pd.DataFrame({"ColumnName1":[1],"ColumnName2":['text']})

Then you have:

In [6]: df
Out[6]: 
   ColumnName1 ColumnName2
0            1        text

Values from single row

If you want to get the values from first row you just need to use:

In [9]: df.iloc[0]
Out[9]: 
ColumnName1       1
ColumnName2    text
Name: 0, dtype: object

Or:

In [10]: df.iloc[0,:]
Out[10]: 
ColumnName1       1
ColumnName2    text
Name: 0, dtype: object

And if you want to get an array instead you can use:

In [11]: df.iloc[0].values
Out[11]: array([1, 'text'], dtype=object)

Values from single cell

If you want the values from a single cell just use:

In [14]: df.iloc[0,0]
Out[14]: 1

In [15]: df.iloc[0,1]
Out[15]: 'text'

Or even with:

In [22]: df.ColumnName1[0]
Out[22]: 1

In [23]: df.ColumnName2[0]
Out[23]: 'text'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.