有没有办法检查pandas数据帧(整个数据帧)中当前行中的所有列值是否小于所有先前行(直到当前行)中的相应列值,并使用以下命令创建新列相应的值为 1 或 0?
最佳答案
考虑数据帧df
np.random.seed(1)
df = pd.DataFrame(np.random.rand(10, 2), columns=list('AB'))
df
A B
0 0.417022 0.720324
1 0.000114 0.302333
2 0.146756 0.092339
3 0.186260 0.345561
4 0.396767 0.538817
5 0.419195 0.685220
6 0.204452 0.878117
7 0.027388 0.670468
8 0.417305 0.558690
9 0.140387 0.198101
选项 1
cummin
与 shift
这里的概念是跟踪到目前为止每列的最小值。如果特定行上的值小于前一行及其之前的所有行,则该值必须是新的最小值。我们可以通过检查它是否小于前一行的最小值来判断这是否为True
。
注意这对于 NaN
值应该可以正常工作。
df.assign(New=(df < df.cummin().shift()).all(1).astype(int))
A B New
0 0.417022 0.720324 0
1 0.000114 0.302333 1
2 0.146756 0.092339 0
3 0.186260 0.345561 0
4 0.396767 0.538817 0
5 0.419195 0.685220 0
6 0.204452 0.878117 0
7 0.027388 0.670468 0
8 0.417305 0.558690 0
9 0.140387 0.198101 0
<小时/>
选项 2
numpy
版本
numpy.minimum
v = df.values
c = np.minimum.accumulate(v[:-1], axis=0)
df.assign(New=np.append(False, (v[1:] < c).all(1)).astype(int))
A B New
0 0.417022 0.720324 0
1 0.000114 0.302333 1
2 0.146756 0.092339 0
3 0.186260 0.345561 0
4 0.396767 0.538817 0
5 0.419195 0.685220 0
6 0.204452 0.878117 0
7 0.027388 0.670468 0
8 0.417305 0.558690 0
9 0.140387 0.198101 0
关于python - 检查当前行中的所有列值是否小于 pandas 数据框中的所有先前行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44556594/