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

133 投票
1 回答
278926 浏览
提问于 2025-04-18 10:08

有没有办法在不知道索引的情况下访问一个序列的第一个元素呢?

假设我有以下这个序列:

import pandas as pd

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

打印出 SUBJECTS

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

我怎么能在不使用索引145的情况下,直接获取到这里的值146呢?

1 个回答

208

使用 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

撰写回答