python将逻辑运算符放在列块上

2024-03-29 14:37:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我将一个数据集加载到pandas数据帧中,如下所示:

n=2
np.random.seed(1)
dt = pd.DataFrame((np.random.rand(5, 2*n+1)*1000).round(), columns=['id', 'x_0', 'y_0', 'x_1', 'y_1'])
>>> dt
    id  x_0  y_0  x_1  y_1
0  417  720    0  302  147
1   92  186  346  397  539
2  419  685  204  878   27
3  670  417  559  140  198
4  801  968  313  692  876

[5 rows x 5 columns]

我知道这只对n=2有效,但是现在我不知道如何为任何n构造列名(但我想这是另一个主题的问题)。在

一般来说,我可以有n个x和y列的块(它们是每月的数据)。在

我需要检查的是在同一个月内x_I和y_I的值是否都超过了某个值,如果在n个月中的任何一个都超过了某个值,则返回1,否则返回0。在

所以,我在摆弄:

^{pr2}$

我想检查x_i值是否超过400和{}是否超过{}。这将产生x和y值的两个数据帧(n列宽),这是可以的。但当我试着:

(dt[range(1, 2*n+1, 2)] > 400) & (dt[range(2, 2*n+1, 2)] > 300)

它不应用&;operator by elements,但返回一个2*n个NAN数据帧:

   x_0  x_1  y_0  y_1
0  NaN  NaN  NaN  NaN
1  NaN  NaN  NaN  NaN
2  NaN  NaN  NaN  NaN
3  NaN  NaN  NaN  NaN
4  NaN  NaN  NaN  NaN

很明显我遗漏了一些东西。问题是背后的逻辑是什么,以及如何使其发挥作用。在

如果我能做到这一点,我会尝试使用any()函数和{}一起使用。在

如有任何建议,我们将不胜感激。在

*编辑 这里还有一个R代码片段,可以解决这个问题。也许我的Python代码的R方法在这里给我“增加了负担”。在

> n=2
> dt <- data.frame(id = c(417, 92, 419, 670, 801),
+                     x_0 = c(720, 186, 685, 417, 968),
+                     y_0 = c(0, 346, 204, 559, 313),
+                     x_1 = c(302, 397, 878, 140, 692),
+                     y_1 = c(147, 539, 27, 198, 876))

> (x <- (dt[,seq(2, 2*n+1, by=2)] > 400) & (dt[,seq(3, 2*n+1, by=2)] > 300))
       x_0   x_1
[1,] FALSE FALSE
[2,] FALSE FALSE
[3,] FALSE FALSE
[4,]  TRUE FALSE
[5,]  TRUE  TRUE
> (result <- apply(x, 1, any, na.rm=T))
[1] FALSE FALSE FALSE  TRUE  TRUE

Tags: columns数据代码idfalsetruepandasby
1条回答
网友
1楼 · 发布于 2024-03-29 14:37:53

它使用按列名的索引,并且不对列使用逻辑运算符,而是使用apply函数遍历行:

n=2
import numpy as np
import pandas as pd

dt = pd.DataFrame((np.random.rand(5, 2*n+1)*1000).round(), columns=['id', 'x_0', 'y_0', 'x_1', 'y_1'])
print dt

def check_x(x):
    value=0
    columns_with_x = [col for col in x.index if 'x_' in col]
    columns_with_y = [col for col in x.index if 'y_' in col]
    for each_col_x in columns_with_x:
        if x[each_col_x] > 400:
            for each_col_y in columns_with_y:
                if x[each_col_y] > 300:
                    value=1
    return value

checked = dt.apply(check_x, axis=1)

print checked

输出:

^{pr2}$

相关问题 更多 >