How to Filter pandas dataframe [Error : list indices must be integers or slices, not str]

Tags: , ,



I have dataframe loaded in colab, my data look like this

id     parent_name_1    parent_name_2
1          NUll              Apricots
2          Apple             Red Apple
3          Null              Red Apple
4          Blueberries       Blueberries
5          Apple             Green Apple
...

this is my code

tm_df1 = pd.DataFrame()
tm_df1 = tm_df1.append(tm_df[type(tm_df['parent_name_1']) == 'Apple'])

when I want to take some of the dataframe and put it into new dataframe I get this Error

TypeError———–Traceback (most recent call last) in ()
1 tm_df1 = pd.DataFrame()
—-> 2 tm_df1 = tm_df1.append(tm_df[type(tm_df[‘parent_name_1’]) == ‘Apple’])
TypeError: list indices must be integers or slices, not str

Answer

If you want to filter out the rows with parent_name_1= “Apple”

use :

tm_df1 = tm_df1.append(tm_df[tm_df['parent_name_1'] == 'Apple'],ignore_index=True)


Source: stackoverflow