user1452759
user1452759

Reputation: 9450

Python: Pandas - Separate a Dataframe based on a column value

Suppose I have a dataframe as shown below:

in:
mydata = [{'subid' : 'B14-111', 'age': 75, 'fdg':1.78},
          {'subid' : 'B14-112', 'age': 22, 'fdg':1.56},]
df = pd.DataFrame(mydata)

out:
       age   fdg    subid
    0   75  1.78  B14-111
    1   22  1.56  B14-112

I want to separe the dataframe to two different dataframes based on the "age" column, as shown below:

out:
   df1: 
           age   fdg    subid
        0   75  1.78  B14-111

   df2:

           age   fdg    subid
        1   22  1.56  B14-112

How can I achieve this?

Upvotes: 3

Views: 8084

Answers (1)

EdChum
EdChum

Reputation: 394041

We can do this directly using boolean condition as the filter:

In [5]:

df1 = df[df.age == 75]
df2 = df[df.age == 22]
print(df1)
print(df2)
   age   fdg    subid
0   75  1.78  B14-111
   age   fdg    subid
1   22  1.56  B14-112

but if you have more age values perhaps you want to group them:

In [13]:
# group by the age column
gp = df.groupby('age')
# we can get the unique age values as a dict where the values are the key values
print(gp.groups)
# we can get a specific value passing the key value for the name
gp.get_group(name=75)
{75: [0], 22: [1]}
Out[13]:
   age   fdg    subid
0   75  1.78  B14-111

We can also get the unique values and again use this to filter the df:

In [15]:

ages = df.age.unique()
for age in ages:
    print(df[df.age == age])
   age   fdg    subid
0   75  1.78  B14-111
   age   fdg    subid
1   22  1.56  B14-112

Upvotes: 10

Related Questions