Home > Software engineering >  multiple get_group with different column values but 1 column
multiple get_group with different column values but 1 column

Time:09-28

I' having trouble finding a straight forward answer on this. What I'm trying to do is get rows that have 125 for their Keycode column value and rows that have 175 for their Keycode column value and put them in 1 dataframe. I thought it would be something like this, but I was incorrect in that thinking. I only get the 125 out to the dataframe. Thank you in advance for any help or calling me mindless...

groups = df.groupby(df.Keycode) # Keycode is the column label I grouped on
onetwofive = groups.get_group('125') # 125 is the column value I'm wanting to pull out
onetwofive.append(groups.get_group('175'))  # 175 is the column value I'm wanting to pull out and append with the 125 group

CodePudding user response:

Use .isin:

output = df[df["Keycode"].isin([125,175])]

CodePudding user response:

This should work:

df[(df.Keycode==125) | (df.Keycode==175)]

Example:

df=pd.DataFrame({'ID':[0,1,2,3,4,5,6,7,8,9], 'Keycode':[125,137,122,125,175,148,175,231,201,150], 'foobar':['f','o','o','b','a','r','f','o','o','b']})

df[(df.Keycode==125) | (df.Keycode==175)]

df:

ID Keycode foobar
0 125 f
1 137 o
2 122 o
3 125 b
4 175 a
5 148 r
6 175 f
7 231 o
8 201 o
9 150 b

Output:

ID Keycode foobar
0 125 f
3 125 b
4 175 a
6 175 f
  • Related