![]() |
[Solved] Delete a line in a dataframe using .reset_index() and .drop() - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: [Solved] Delete a line in a dataframe using .reset_index() and .drop() (/thread-36497.html) |
[Solved] Delete a line in a dataframe using .reset_index() and .drop() - ju21878436312 - Feb-25-2022 Hi out there, I'd like to delete a line in the dataframe "df_new". Why does it not work? I get the error: "KeyError: '[0] not found in axis". import pandas as pd import numpy as np data = {'x': [0,1, 2,3,4,5,6,7,8], 'y': [60, 23, 24,42,56,10,20,25,13], 'comment': ["false", "true","true","true","true","true","true","true","true"], } df = pd.DataFrame(data) df_new = df.loc[df['comment'] == "true"] # This works fine df = df.drop([0]) # This creates an error: KeyError: '[0] not found in axis' df_new = df_new.drop([0]) print(type(df)) # <class 'pandas.core.frame.DataFrame'> print(type(df_new)) # <class 'pandas.core.frame.DataFrame'> RE: Delete a line in a dataframe - deanhystad - Feb-25-2022 Indexing in pandas is not like indexing a list. Deleting a row does not change the index of the trailing rows. In your example df_new doesn't have an index[0]. You filtered out index[0] when when creating df_new. df_new starts at index[1] You can reset the index using reset_index() https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html import pandas as pd data = {'x': [0,1, 2,3,4,5,6,7,8], 'y': [60, 23, 24,42,56,10,20,25,13], 'comment': ["false", "true","true","true","true","true","true","true","true"], } df = pd.DataFrame(data) df_new = df.loc[df['comment'] == "true"] print(df_new) df_new = df_new.reset_index(drop=True) print(df_new) df_new = df_new.drop(0) print(df_new) RE: Delete a line in a dataframe - ju21878436312 - Feb-25-2022 Thank you very much! ![]() |