【问题标题】:A simple way to replace all column values in a loop of a dataframe according to another column根据另一列替换数据框循环中所有列值的简单方法
【发布时间】:2021-10-22 13:38:24
【问题描述】:

我想更改正确选项的值,或者只是使用正确选项值中给出的信息创建一个新列,我尝试循环遍历索引并更改它,但比较代码不起作用,我什至尝试了 iteritems之前但失败了。有人可以告诉如何解决这个问题。

 In[] df
Out[] **ques opt1 opt2 opt3 opt4  correctOpt**
        q1   red  blue grey green opt1
        q2   red  blue grey green opt3

我试过了

for col in df.index:
 df.replace(to_replace=df['Correct Option'][col], value = df[[col],['Correct option']],[col]) 

得到位置参数跟随关键字参数错误

我正在尝试将其作为输出或新列中的相同列行值

Out[] correctOpt
      red
      grey

谢谢

【问题讨论】:

    标签: python pandas dataframe data-science data-wrangling


    【解决方案1】:

    你可以像下面这样使用apply函数:

    df = pd.DataFrame([['q1','red','blue','grey','green','opt1'],
                        ['q2','red','blue','grey','green','opt3']], 
                        columns=['ques','opt1','opt2','opt3','opt4','correctOpt'])
    
    df.apply(lambda row: row['opt'+row['correctOpt'][3]], axis=1)
    

    apply 函数将自定义函数应用于 DataFrame 中的每一行。 'axis=1' 为自定义函数提供 DataFrame ROW 作为参数(而不是列),然后 row['correctOpt'][3] 获取正确的选项编号,并且 row['opt'+row['correctOpt'] [3]] 从 opt 列中获取结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-02
      • 2014-09-06
      • 2021-06-29
      • 2020-09-01
      • 2021-06-12
      • 2022-06-23
      相关资源
      最近更新 更多