0

I have the following dataframne:

df
                Name    Jan Feb Mar
Description             
New             A       34  32  54
Old             B       65  98  05
Retired         C       96  26  43

Description is an index column.

I am trying to assign a value to variable as follows:

variable = df[(df['Description']=='Retired') & (df['Name']=='C')]["Jan"]

But i am getting an error:

ValueError: setting an array element with a sequence.

Is there a way to do it?

1 Answer 1

2

Use DataFrame.loc with compare index - output is Series - with one or more values:

variable = df.loc[(df.index=='Retired') & (df['Name']=='C'), "Jan"]
print (variable)
Description
Retired    96
Name: Jan, dtype: int64

If need select first and always exist at least one value use:

print (variable.iat[0])
96

But if possible no match, then is returned empty Series and cannot select like above, then is possible use next-iter trick with possible set default value if empty Series:

variable = df.loc[(df.index=='Retired') & (df['Name']=='another'), "Jan"]
print (variable)
Series([], Name: Jan, dtype: int64)

print (next(iter(variable), 'no match'))
no match

Another better solution is add Name to index for MultiIndex and then select by tuple if need scalar output:

df = df.set_index('Name', append=True)

variable = df.loc[('Retired','C'), "Jan"]
print (variable)
96
Sign up to request clarification or add additional context in comments.

4 Comments

Since i am going to use this variable to further code, when i enter variable, it should show only 96, nothing else. Is it possible to use df.loc and df.at in a single line of code? no_days = df.loc[df.index,'Name'].at['Jan'] . I am not able to use this since i have to filter the description column also.
@RSM - second solution with df = df.set_index('Name', append=True) variable = df.loc[('Retired','C'), "Jan"] print (variable) is not possible use?
Sorry @jezreal, i still do not get a single number i get same output as Description Name Retired C 96 Name: Jan, dtype: float64
@RSM - In last paragraph solution?

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.