0

Given

import pandas as pd
df = pd.DataFrame({'lowercase':['a','b','c','d']},
                       index=[0,1,3,4])

# print(df)

print(df['lowercase'].iat[0])

I can get 'a', but I want to get the first index (which is 0) and 'a' return as two values, how should I do?

5
  • 2
    Use df.index[0] Commented Jun 14, 2020 at 14:16
  • 1
    df.index[0] ? what do you mean by and 'a' return as two values, ? Commented Jun 14, 2020 at 14:16
  • Thanks @ScottBoston @anky a=df['lowercase'].index[0] b=df['lowercase'].iat[0] Can this be simplify in one line? Commented Jun 14, 2020 at 14:18
  • 1
    a, b = df['lowercase'].index[0], df['lowercase'].iat[0]? It's one line :) Commented Jun 14, 2020 at 14:22
  • 1
    a,b = [*df['lowercase'].head(1).items()][0] ? Commented Jun 14, 2020 at 14:24

1 Answer 1

1

You can use df.itertuples which returns a map object.

def get_item(idx):
    it = df.itertuples()
    while idx:
        next(it)
        idx = idx-1
    return next(it)

a,b = get_item(0)
# a = 0 , b = 'a'
c,d = get _item(1)
# c = 1, d = 'b'

You can even get a slice using islice from itertools.

def get_item(start,end=None):
    it = df.itertuples()
    if end is None:
        while idx:
            next(it)
            idx = idx-1
        return next(it)
    return list(map(tuple,islice(it,start,end)))

get_item(1, 4)
# [(1, 'b'), (3, 'c'), (4, 'd')]

If you only want first value

a,b = next(df.itertuples())
# a = 0, b = 'a'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.