pandas 以字符串形式返回索引值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40950944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:34:06  来源:igfitidea点击:

Return index value as string

pythonpandas

提问by Stephen Juza

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:

当我打印 String_to_be_returned 时,我得到了这个:

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

Index(['美国'], dtype='object', name='Country Name')

回答by jezrael

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

我认为您需要添加[0]select 第一个值indexarray

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