Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于条件在数据帧中迭代并赋值_Python_For Loop_Iteration - Fatal编程技术网

Python 基于条件在数据帧中迭代并赋值

Python 基于条件在数据帧中迭代并赋值,python,for-loop,iteration,Python,For Loop,Iteration,我有一个由8列组成的熊猫数据帧(c1到c7,最后一列称为total)c1到c7是0和1 列总数应为c1至c7内序列中最大数量1的赋值c1到c7表示工作日,因此7应翻转为1 例如,如果我们有和初始数据帧类似的df: | c1 | c2 | c3 | c4 | c5 | c6 | c7 | total | |:---|:---|:---|: --|:---|:---|:---|:-----:| | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | | 0 | 0

我有一个由8列组成的熊猫数据帧(
c1
c7
,最后一列称为
total
)<代码>c1到
c7
0
1

列总数应为
c1
c7
内序列中最大数量1的赋值
c1
c7
表示工作日,因此7应翻转为1

例如,如果我们有和初始数据帧类似的df:

| c1 | c2 | c3 | c4 | c5 | c6 | c7 | total |
|:---|:---|:---|: --|:---|:---|:---|:-----:|
| 1  | 1  | 1  | 1  | 1  | 0  | 0  |  0    |
| 0  | 0  | 1  | 0  | 0  | 0  | 0  |  0    |
| 1  | 1  | 0  | 1  | 1  | 0  | 0  |  0    |
| 1  | 1  | 1  | 0  | 1  | 1  | 1  |  0    |
| 1  | 0  | 1  | 1  | 1  | 0  | 1  |  0    |
| 1  | 0  | 1  | 0  | 1  | 0  | 1  |  0    |
| 0  | 1  | 0  | 1  | 0  | 1  | 0  |  0    |
我最初的想法是创建一个包含if语句的循环,以评估列中的条件,并将值分配给列total

i = "c1"
d = 
for i in df.iloc[:,0:7]:
    if df[i] == 1 and df[i-1] == 1:
    df["total"]:= df["total"] + 1
我希望df看起来像:

| c1 | c2 | c3 | c4 | c5 | c6 | c7 | total |
|:---|:---|:---|: --|:---|:---|:---|:-----:|
| 1  | 1  | 1  | 1  | 1  | 0  | 0  |  5    |
| 0  | 0  | 1  | 0  | 0  | 0  | 0  |  1    |
| 1  | 1  | 0  | 1  | 1  | 0  | 0  |  2    |
| 1  | 1  | 1  | 0  | 1  | 1  | 1  |  6    |
| 1  | 0  | 1  | 1  | 1  | 0  | 1  |  3    |
| 1  | 0  | 1  | 0  | 1  | 0  | 1  |  2    |
| 0  | 1  | 0  | 1  | 0  | 1  | 0  |  1    |
我还没有得到一个结果,我试图一步一步地构建,但在if语句求值中不断得到一个错误

ValueError:序列的真值不明确。使用a.empty, a、 bool()、a.item()、a.any()或a.all()

循环中的bug
  • df[i-1]
    当i==0时将抛出错误
  • df[i]
    给出所有行的第i列的值
  • 7然后应翻转为1
    :代码中缺少此部分

  • 要将行的尾部(7)翻转回头部(1),请在尾部放置一份行的副本,然后检查是否有1。这也可以通过将行循环两次并使用模运算符来实现。检查此项了解更多详细信息

    最后一行的预期结果是否应为1?如果是2,你能解释为什么吗?是的,我很抱歉,确实是1
    df = pd.DataFrame([[ 1,1,1,1,1,0,0], [0,0,1,0,0,0,0],[1,1,0,1,1,0,0]])
    
    def fun(x):
        count = 0; 
        result = 0; 
        n = len(x)
        for i in range(0,2*n):
            if x[i % n] == 0:
                result = max(result, count)
                count = 0
            else:
                count += 1
        return result
    
    df['total'] = df.apply(lambda x: fun(x), axis=1)
    
        0   1   2   3   4   5   6   total
    0   1   1   1   1   1   0   0   5
    1   0   0   1   0   0   0   0   1
    2   1   1   0   1   1   0   0   2