Home > OS >  Filter for column value and set its other column to an array
Filter for column value and set its other column to an array

Time:10-02

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!

CodePudding user response:

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)
  • Related