我有一个如下所示的df:
id
0 aaa
1 bbb
2 ccc
3 ddd
我想创建并设置列'win / lose',其中从索引0开始的每第3行都等于TRUE。
新df应该如下所示:
id win/lose
0 aaa True
1 bbb False
2 ccc False
3 ddd True
我可以像这样选择每第3行:
df[df.index % 3 == 0]
我不知道如何将第三行的列设置为TRUE,而其他每一行都是FALSE。
我尝试了这个FOR循环,但是我没有做正确的事。
for row in df.iterrows():
df['Win'][df['Win'].index % 3 == 0] = 'TRUE'
答案 0 :(得分:3)
最快的方法可以是直接检查索引并为其分配:
%time df['win/lose'] = df.index % 3 == 0
CPU times: user 1.39 ms, sys: 71 µs, total: 1.47 ms
Wall time: 1.44 ms
您也可以使用Apply检查索引,但是这种方法比较慢:
%time df['win/lose'] = df.apply(lambda x: x.index % 3 == 0)
CPU times: user 3.48 ms, sys: 83 µs, total: 3.56 ms
Wall time: 3.5 ms
答案 1 :(得分:2)
您可以尝试一下。
df.assign(win_loss = df.index%3 == 0)
id win_loss
0 aaa True
1 bbb False
2 ccc False
3 ddd True