Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter for column value and set its other column to an array

I have a df such as

Letter | Stats
  B       0
  B       1
  C       22
  B       0
  C       0
  B       3

How can I filter for a value in the Letter column and also then convert the stats column for that value into an array?

Basically want to filter for B and convert the Stats column to an array, Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

here is one way to do it

# function received, dataframe and letter as parameter
# return stats values as list for the passed Letter
def grp(df, letter):
    return df.loc[df['Letter'].eq(letter)]['Stats'].values.tolist()

# pass the dataframe, and the letter 
result=grp(df,'B')
print(result)

[0, 1, 0, 3]

data used

data ={'Letter': {0: 'B', 1: 'B', 2: 'C', 3: 'B', 4: 'C', 5: 'B'},
 'Stats': {0: 0, 1: 1, 2: 22, 3: 0, 4: 0, 5: 3}}
df=pd.DataFrame(data)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading