Anton Protopopov
Anton Protopopov

Reputation: 31692

Get first value of column in dataframe in pandas with offset indices

I have a dataframe with offset indices and I'd like to access the first value of interested column:

df = pd.DataFrame({"a": [0,1,2], "b":[3,4,5]}, index=[5,6,7])
In [20]: df
Out[20]:
   a  b
5  0  3
6  1  4
7  2  5

None of the .ix, .loc methods of pandas dataframe didn't help (or I used them inappropriate):

In [24]: df.ix[0,"a"]
KeyError: 0

In [27]: df["a"][0]
KeyError: 0

I could do it with reset_index method but I'd like to keep original dataframe
I found solution but I think it's not the best:

In [29]: df["a"].values[0]
Out[29]: 0

Upvotes: 2

Views: 6644

Answers (2)

EdChum
EdChum

Reputation: 394419

Use iloc[0] to access the first elements:

In [193]:
print(df['a'].iloc[0])
print(df['b'].iloc[0])

0
3

or head:

In [194]:
df.head(1)

Out[194]:
   a  b
5  0  3

Upvotes: 2

MhP
MhP

Reputation: 56

try this ... [df.loc[currentIndex,'a'] for currentIndex in list(df.index)]

to just get first element for column a try this

df.loc[list(df.index)[0],'a']

Upvotes: 0

Related Questions