HimanAB HimanAB - 10 months ago 58
Python Question

Return the int value for a specific column in a pandas data frame

In my data frame DF I have a column called 'A' and its values are integer values. However when I want to retrieve the value of A for a specific row using


it returns an object of shape (1,) that is not int because int does not have a shape. I want int because I want to use this value as an index entry to another numpy array. How can I retrieve the value of A so that it's an int value?

Answer Source

In general, a condition of the form

DF.someCondition = condition

may be True more than once. That is why


returns an object of shape (1,) rather than a scalar value. If you are certain that the condition is True only once, then you can extract the scalar value using item


However, as MaxU suggested, it is better to use .loc to avoid chained-indexing:

DF.loc[DF.someCondition=condition, 'A'].item()

For example,

import numpy as np
import pandas as pd

df = pd.DataFrame(np.arange(6).reshape(3,2), columns=list('AB'))
# 1    2
# Name: A, dtype: int64

df.loc[df['B']==3, 'A'].item()
# 2