Iterate through a list of dataframes to drop particular rows Pandas

后端 未结 2 1844
抹茶落季
抹茶落季 2021-01-25 05:13

In my previous question where I asked to drop particular rows in Pandas

With help, I was to drop rows that before 1980. The \'Season\' column (that had the years) were i

2条回答
  •  灰色年华
    2021-01-25 06:01

    If you want to modify the list in-place :

    for index in range(len(df_list)):
        df_list[index] = df_list[index].loc[df_list[index]['Season'].str.split('-').str[0].astype(int) > 1980]
    

    When you're looping through the list object itself, it creates a new object at each iteration, that's getting erased at each turn.

    If you're looping using the length of the list, and accessing your data through the index, you will modify the list itself, and not the copy you made with for some_copy_item in df_list.


    Minimal example :

        arr = [1, 2, 3, 4, 5]
        print(arr) # [1, 2, 3, 4, 5]
    
        for number in arr:
            number += 1
        print(arr) # [1, 2, 3, 4, 5]
    
        for idx in range(len(arr)):
            arr[idx] += 1
        print(arr) # [2, 3, 4, 5, 6]
    

提交回复
热议问题