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