I have a for loop that goes through a data frame and asks if we want to delete each row. No matter what I do I cannot get the row to drop if I say Y.
for index, row in df1.iterrows():
Check3 = input("Are you sure you want to Delete this question? (Y/N) ")
if Check3 == "Y": #Edited question to remove indent to match my code
df1.drop(index, inplace=True)
My df is this: df1 =
12,What is your number?
10,What is your email?
6,What is your Job title?
30,What color is your car?
Thanks for any help!
CodePudding user response:
[Edit] I tried this and it worked for me. Not sure why it's not working for you. Maybe give us your dataframe (or sample of it) to test it.
>>> df1 = pd.DataFrame({'col1':['-1', '-2', -3, -4], 'col2':['-2', '-6', 44, 66], 'col3':['15', 16, 17, 29]})
>>>
>>> for index, row in df1.iterrows():
... Check3 = input("Are you sure you want to Delete this question? (Y/N) ")
... if Check3 == "Y":
... df1.drop(index, inplace=True)
...
Are you sure you want to Delete this question? (Y/N) Y
Are you sure you want to Delete this question? (Y/N) N
Are you sure you want to Delete this question? (Y/N) Y
Are you sure you want to Delete this question? (Y/N) N
>>>
>>> df1
col1 col2 col3
1 -2 -6 16
3 -4 66 29
CodePudding user response:
This code works from me.
Note: I am using the "walrus" operator for python 3.8
df = pd.DataFrame({'Questions':[f"Question {i}" for i in range(1,6)],
'Text':["What is your number?", "What is your email?",
"What is your job title?", "What color is your car?",
"Do you have children?"]})
for indx, row in df.iterrows():
print(row)
print('\n')
if (check3 := input("Are you sure you want to delete this row? ") == "Y"):
df.drop(indx, inplace=True)
print('\n')
Output:
Questions Question 1
Text What is your number?
Name: 0, dtype: object
Are you sure you want to delete this row? N
Questions Question 2
Text What is your email?
Name: 1, dtype: object
Are you sure you want to delete this row? Y
Questions Question 3
Text What is your job title?
Name: 2, dtype: object
Are you sure you want to delete this row? N
Questions Question 4
Text What color is your car?
Name: 3, dtype: object
Are you sure you want to delete this row? N
Questions Question 5
Text Do you have children?
Name: 4, dtype: object
Are you sure you want to delete this row? Y
And, print(df)
Questions Text
0 Question 1 What is your number?
2 Question 3 What is your job title?
3 Question 4 What color is your car?