In pandas, Deleting the existing row before adding the new row by loc function

I have a dataset with 1705 rows X 7columns
Max loc:1704
Max iloc:1705
Here my code is:

data = data.drop(1703,inplace=True)
data.loc[len(data)]=["list"]

when running this code the 1703 row will be deleted. the max of loc and iloc became the same. when i add any new rows it will assign to the existing row there the new rows places over the existing rows.
what is the solution for this because we cannot use iloc for adding new row we can only assign to existing using iloc

I have tried this code:

data = data.append(["List"],ignore_index=True)

But it is not the effective way

  • why do you want to do this? Adding rows this way is not always the best approach

    – 

You can try like this

import pandas as pd

# Assuming 'data' is your DataFrame
data = pd.DataFrame({
    'Column1': [1, 2, 3, 4],
    'Column2': ['A', 'B', 'C', 'D']
})

# Drop the row at index 2 (0-based index)
data.drop(2, inplace=True)

# Reset the index to reflect the changes
data.reset_index(drop=True, inplace=True)

# Add a new row at the end
data.loc[len(data)] = [5, 'E']

print(data)

Output:

   Column1 Column2
0        1       A
1        2       B
2        4       D
3        5       E

If you really need to add a row ensuring it’s not already existing, then add a index that is greater to the existing maximum.

Also, don’t use inplace=True if you reassign the output.

data = data.drop(1703)
data.loc[data.index.max()+1] = ["list"]

Example:

data = pd.DataFrame('x', index=range(1705), columns=(0, 1))

print(data.tail())
#       0  1
# 1700  x  x
# 1701  x  x
# 1702  x  x
# 1703  x  x
# 1704  x  x

data = data.drop(1703)
data.loc[data.index.max()+1] = ['y', 'z']

print(data.tail())
#       0  1
# 1700  x  x
# 1701  x  x
# 1702  x  x
# 1704  x  x
# 1705  y  z

Leave a Comment