Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return index value as string

Tags:

python

pandas

I'm trying to return the index of a value as a string. Other questions on here that I saw had it return indexes as lists.

The error that is thrown is: You returned a variable of type and we expected a type of

My code:

String_to_be_returned=(df['Column'].index[df['Column']==2])

Example:

When I print String_to_be_returned, I get this:

Index(['United States'], dtype='object', name='Country Name')

like image 452
Stephen Juza Avatar asked Dec 03 '16 18:12

Stephen Juza


People also ask

Can an index be a string?

Strings are ordered sequences of character data, 00:15 and the individual characters of a string can be accessed directly using that numerical index. String indexing in Python is zero-based, so the very first character in the string would have an index of 0 , 00:30 and the next would be 1 , and so on.

How do you return an index value?

The price return calculation – the return from the index in percentage terms – is simply the difference in value between the two periods divided by the beginning value. Another way to calculate these returns would be to sum up the weighted returns of each constituent security in the index portfolio.

How do you find the index of a string?

You can get the character at a particular index within a string, string buffer, or string builder by invoking the charAt accessor method. The index of the first character is 0; the index of the last is length()-1 .


1 Answers

I think you need add [0] for select first value of index which is array:

String_to_be_returned= df[df['Column']==2].index[0]

Sample:

df = pd.DataFrame({'Column':[1,2,3],
                   'Column1':[4,5,6]
                   }, index=['Slovakia','United States','Mexico'])

print (df)
               Column  Column1
Slovakia            1        4
United States       2        5
Mexico              3        6

String_to_be_returned= df[df['Column']==2].index[0]
print (String_to_be_returned)
United States

String_to_be_returned= df.index[df['Column']==2][0]
print (String_to_be_returned)
United States
like image 55
jezrael Avatar answered Oct 19 '22 06:10

jezrael