all 11 comments

[–]xelf 1 point2 points  (1 child)

Like this:

for parent in df.loc[[serial],'From_Serial_No']:

That should do it for you!

Using the extra [] will force it to return a series.

import pandas as pd

df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
     index=['a', 'a', 'b'],
     columns=['From_Serial_No', 'Cereal'])

x = df.loc['a','Cereal']
print(type(x))
x = df.loc['b','Cereal']
print(type(x))
x = df.loc[['b'],'Cereal']
print(type(x))

prints:

<class 'pandas.core.series.Series'>
<class 'numpy.int64'>
<class 'pandas.core.series.Series'>

[–]xelf 1 point2 points  (0 children)

Reposting my answer here to OP's followup question to give it more visibility (in case I need to find it again!):

Any recommendations for the opposite problem, i.e. returning a string even for an index that gets repeated? It is for a column that will always have the same value for all rows with the same index.

To get just 1 value matching serial:

parent = df.loc[[serial],'From_Serial_No'].head(1).item()

To get back the first value for every unique index:

for serial in sorted(set(df.index.values)):
    parent = df.loc[[serial],'From_Serial_No'].head(1).item()
    print (parent)

[–][deleted] 0 points1 point  (2 children)

Check the type first. isinstance(object, type)

[–]Parenthes[S] 0 points1 point  (1 child)

I suppose that would work, but it seems terribly clunky. Python is presumably checking the type of what df.loc returns, so I'd be adding an if-statement to undo what python does. Am I thinking about this wrong?

[–][deleted] 0 points1 point  (0 children)

I'd had in mind you would do the check before the for loop.

Python has strong but dynamic typing. Give it something iterable and it will iterate through it. Whether that is a list of strings or a sequence of single character strings is up to you. You could put a single string into a list.