简体   繁体   English

用 1 和 0 填充 DataFrame

[英]Filling DataFrame with 1s and 0s

I have two pandas dataframes one is an answer key which looks like this我有两个 Pandas 数据框,一个是答案键,看起来像这样

     0     1 2 3 4 5 6 7 8 9
 0 TTTTKEY B C B A D A D D C
 

The other dataframe has answers from students which looks like this另一个数据框有学生的答案,看起来像这样

     0  1 2 3 4 5 6 7 8 9
0   182 C C C A D A D D C 
1   184 C C B A D C A D C

I am wondering how I could change the values to 1's if the answers from students match the answer key and change the values to 0's if the answers from students do not match the answer key.我想知道如果学生的答案与答案键匹配,如何将值更改为 1,如果学生的答案与答案键不匹配,则如何将值更改为 0。 I think this could use a nested for loop but there might be a different way to to this.我认为这可以使用嵌套的 for 循环,但可能有不同的方法。

You can make use of np.where() for this您可以np.where()使用np.where()

import numpy as np

equals = np.where(df1.values[:,1:] == df2.values[:,1:], 1, 0)
df2.iloc[:,1:] = equals
In [34]: df2
Out[34]: 
     0  1  2  3  4  5  6  7  8  9
0  182  0  1  0  1  1  1  1  1  1
1  184  0  1  1  1  1  0  0  1  1

assume dataframes are called df1 and df2 , you can run假设数据帧被称为df1df2 ,你可以运行

is_equal = df1.values[:,1:] == df2.values[:,1:]

is_equal will be numpy array with ones and zeros. is_equal将是带有 1 和 0 的 numpy 数组。 You can convert it to 0s and 1s with is_equal.astype(int) .您可以使用is_equal.astype(int)将其转换为 0 和 1。 You can wrap this in a dataframe, and add back in the 0 column if you wish.您可以将其包装在一个数据框中,并根据需要将其添加回 0 列。

Use:用:

cols = df_2.columns
df_2[cols[1:]] = df_2[cols[1:]].eq(df_1[cols[1:]].loc[0]).astype(int)

Output:输出:

     0  1  2  3  4  5  6  7  8  9
0  182  0  1  0  1  1  1  1  1  1
1  184  0  1  1  1  1  0  0  1  1

Simplest way is to do something like this:最简单的方法是做这样的事情:

for i in range(1, 9 + 1): # Assuming 9 is the last question number
    students[i] = students[i] == answers.loc[0][i]

Your resulting dataframe will contain True or False instead of 1s and 0s but I think it solves your problem您生成的数据框将包含 True 或 False 而不是 1 和 0,但我认为它可以解决您的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM