Python 在不知道索引的情况下获取 Series 的第一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24273130/
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-08-19 04:21:51  来源:igfitidea点击:

Get first element of Series without knowing the index

pythonpandasdataframeserieshead

提问by Hello lad

Is that any way that I can get first element of Seires without have information on index.

这是我可以在没有 index.html 信息的情况下获得 Seires 的第一个元素的任何方式吗?

For example,We have a Series

例如,我们有一个系列

    import pandas as pd
    key='MCS096'
    SUBJECTS=pd.DataFrame({'ID':Series([146],index=[145]),\
                   'study':Series(['MCS'],index=[145]),\
                   'center':Series(['Mag'],index=[145]),\
                   'initials':Series(['MCS096'],index=[145])
                   })

prints out SUBJECTS:

打印出主题:

    print (SUBJECTS[SUBJECTS.initials==key]['ID'])
    145    146
    Name: ID, dtype: int64

How can I get the value here 146 without using index 145?

如何在不使用索引 145 的情况下获得 146 的值?

Thank you very much

非常感谢

采纳答案by Andy Hayden

Use iloc to access by position (rather than label):

使用 iloc 按位置(而不是标签)访问:

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]: 
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]: 
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1