Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selecting a specific value from a data frame

Tags:

python

pandas

I am trying to select a value from a dataframe. But the problem is the output is with data type and column name. Here is my data frame which i am reading from a csv file,

Name,Code
blackberry,1
wineberry,2
rasberry,1
blueberry,1
mulberry,2

And here is my testing code-

dataFrame=pd.read_csv("test.csv")
value = dataFrame.loc[dataFrame['Name'] == 'rasberry']['Code']
print(value)
strvalue=str(value)
if(strvalue=="1"):
    print("got it")

The expected ouput of value would be 1 but it is

2  1\nName: Code, dtype: int64

and that's why the if condition is not working. How can I get the specific value? I am using pandas

like image 294
sovon Avatar asked Jan 29 '17 20:01

sovon


People also ask

How do you select a specific value in a data frame?

Select Data Using Location Index (. This means that you can use dataframe. iloc[0:1, 0:1] to select the cell value at the intersection of the first row and first column of the dataframe. You can expand the range for either the row index or column index to select more data.

How do you access a particular element in a data frame?

By using at and iat attributes We can also access a single value of a DataFrame with the help of “at” and “iat” attributes. Access a single value by row/column name. At and iat take two arguments. If we pass only one argument, then it will generate an error.

How do you select a specific index in a DataFrame?

So, if you want to select the 5th row in a DataFrame, you would use df. iloc[[4]] since the first row is at index 0, the second row is at index 1, and so on. . loc selects rows based on a labeled index.


1 Answers

The value you get is a Series object. You can use .iloc to extract the value from it:

value.iloc[0]
# 1

Or you can use .values to extract the underlying numpy array and then use index to extract the value:

value.values[0]
# 1
like image 158
Psidom Avatar answered Oct 05 '22 22:10

Psidom