【问题标题】:Pandas Dataframe dropping and/or replacing valuesPandas Dataframe 删除和/或替换值
【发布时间】:2022-09-30 23:29:00
【问题描述】:

我有一个充满问题的 Pandas 数据框。我的程序遍历每个问题,并询问用户问题是否可以,或者是否需要更改或从矩阵中删除 - 我无法得到任何一个。

df1 = pd.read_csv(\'questions.csv\', usecols=[\'question_id\',\'question\'])
for index, row in df1.iterrows():
 print(row[\'question\'])
 Check1 = input(\"Is the following question correct? (Y/N): \")
 if Check1 == \"Y\":
    continue
 elif Check1 == \"N\":
    Check2 = input(\"Is this question Needed? (Y/N):\")
     if Check2 == \"N\":
         Check3 = input(\"Are you sure you want to Delete this question? (Y/N)\")
         if Check3 == \"Y\":
             df1.drop(df1.index[index], inplace=True)
     elif Check2 == \"Y\":
         Check4 = input(\"Please rewrite the question: \")
         df1[\'question\'] = df1.replace([\'question\'],\'Check4\')

寻求 df1.drop 的帮助 - 如果我需要删除整行。 或 df1.replace 如果我只需要替换一个单元格值。

编辑: 这是我的数据集 - 数字是标识符:

question_id,question
12,What is your number?
10,What is your email?
6,What is your Job title?
30,What color is your car?]
  • 你能展示和/或分享你的数据集样本吗?
  • 添加到主要问题!

标签: python pandas dataframe loops drop


【解决方案1】:

要删除用户选择的行/问题,您可以使用pandas.DataFrame.drop 并将行的index 作为标签传递。并且要替换用户选择的要改写的特定单元格/问题的值,您可以使用pandas.DataFrame.loc。

您的代码如下所示:

for index, row in df1.iterrows():
    print(row['question'])
    Check1 = input("Is the following question correct? (Y/N): ")
    if Check1 == "Y":
        continue
    elif Check1 == "N":
        Check2 = input("Is this question Needed? (Y/N):")
        if Check2 == "N":
            Check3 = input("Are you sure you want to Delete this question? (Y/N)")
            if Check3 == "Y":
                 df1.drop(index, inplace=True)
        elif Check2 == "Y":
            Check4 = input("Please rewrite the question: ")
            df1.loc[index, 'question'] = Check4

【讨论】:

  • 谢谢! df1.loc 运行良好,但 df1.drop 根本不工作。不知道为什么。
猜你喜欢
  • 2019-08-15
  • 2021-07-30
  • 2018-11-14
  • 1970-01-01
  • 1970-01-01
  • 2017-07-04
  • 2014-06-12
  • 1970-01-01
相关资源
最近更新 更多