How to create a new dataFrame based on some column values?

Question:

I have a dataframe which has a column Flag whose values are either True or False. I want to create a new dataframe whose column Flag’s values must be all True.

df = {'Name':['Tom', 'nick', 'krish', 'jack'],
      'Age':['12', '23', '25', '16'],
      'Flag':[True, False, False, True]}

I want get a new df whose Flags are True, and also drop this Flag column:

df = {'Name':['Tom', 'jack'],
       'Age':['12', '16']}
Asked By: marlon

||

Answers:

Use boolean indexing with boolean column, so compare by True is not necessary:

df = pd.DataFrame(df)    

You can select some columns only by list use DataFrame.loc:

df1 = df.loc[df['Flag'], ['Name','Age']]

Or use and remove Flag use DataFrame.pop:

df1 = df[df.pop('Flag')]

Or delete Flag after selecting add DataFrame.drop:

df1 = df[df['Flag']].drop('Flag', axis=1)

print (df1)
   Name Age
0   Tom  12
3  jack  16
Answered By: jezrael

Use boolean masking and drop() method:

resultdf=df[df['Flag']==True].drop(columns=['Flag'])

OR

You can also use where() method

resultdf=df.where(df['Flag']==True).dropna().drop(columns='Flag')

Output:

print(resultdf)

    Name    Age
0   Tom     12
3   jack    16

If you want index starting from 0 then just chain reset_index() method:

resultdf=df[df['Flag']==True].drop(columns=['Flag']).reset_index(drop=True)

OR

resultdf=df.where(df['Flag']==True).dropna().drop(columns='Flag').reset_index(drop=True)

Output:

print(resultdf)

    Name    Age
0   Tom     12
1   jack    16
Answered By: Anurag Dabas

First make it a dataframe:

df = pd.DataFrame({'Name':['Tom', 'nick', 'krish', 'jack'],
  'Age':['12', '23', '25', '16'],
  'Flag':[True, False, False, True]})

Then you can do as below:

df.loc[[0,3] ,["Name","Age"]]

Result will be like:

    Name    Age
0   Tom     12
3   jack    16
Answered By: berkayln
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.