选择数字列值通过openpyxl改变符号的行

时间:2019-06-19 18:52:59

标签: python-3.x openpyxl

我正在学习Python和openpyxl,以便在大型xlsx工作簿上进行数据分析。我有一个for循环,可以循环访问整列。这是一些示例数据:

ROW:  VALUE:
1      1
2      2
3      3
4      4
5     -4
6     -1
7     -6
8      2
9      3
10    -3

我想打印出其中值从正变为负,反之亦然的行。因此,在上面的示例中,第5、8和10行将在控制台中打印。如何在if循环中使用for语句来遍历openpyxl上的一列?

到目前为止,我可以在列中打印所有单元格:

import openpyxl
wb = openpyxl.load_workbook('ngt_log.xlsx')
sheet = wb.get_sheet_by_name('sheet1')
for i in range(1, 10508, 1):   # 10508 is the length of the column
    print(i, sheet.cell(row=i, column=6).value)

我的想法是在if循环内添加一个for语句:

for i in range(1, 10508, 1):   # 10508 is the length of the column
    if(( i > 0 and (i+1) < 0) or (i < 0 and (i+1) > 0)):
        print((i+1), sheet.cell(row=i, column=6).value)

但这不起作用。我是否正确制定了if语句?

4 个答案:

答案 0 :(得分:1)

在我看来,您的陈述与自己矛盾

function pos(str, char) {
    let pos = 0
    const ret = []
    while ( (pos = str.indexOf(char, pos + 1)) != -1) {
        ret.push(pos)
    }
    return ret
}

function truncate(str, len) {
    if (str.length < len)
        return str

    const allPos = [  ...pos(str, '!'), ...pos(str, '.'), ...pos(str, '?')].sort( (a,b) => a-b )
    if (allPos.length === 0) {
        return str.substr(0, len)
    }

    for(let i = 0; i < allPos.length; i++) {
        if (allPos[i] > len) {
            return str.substr(0, allPos[i-1] + 1)
        }
    }
}

module.exports = truncate

我用普通英语写了>和<符号,但是如果i大于0,则i + 1永远不会小于0,反之亦然,因此它们将永远无法工作,因为两者都不成立。

答案 1 :(得分:1)

您需要先获取sheet.cell值,然后然后进行比较:

end_range = 10508
for i in range(1, end_range):
    current, next = sheet.cell(row=i, column=6).value, sheet.cell(row=i+1, column=6).value
    if current > 0 and next < 0 or current < 0 and next > 0:
        print(i+1, next)

我很确定数学库中有一个sign()函数,但有点过头了。您可能还想弄清楚如果值为0,该怎么办。

答案 2 :(得分:0)

您可以编写规则以选择符号已更改的行,并将其放入生成器表达式中,而无需使用额外的内存,例如:

pos = lambda x: x>=0
keep = lambda s, c, i, v: pos(s[c][x].value)!=pos(v.value)
gen = (x+1 for x, y in enumerate(sheet['f']) if x>0 and keep(sheet, 'f', x-1, y))

然后,当您需要知道符号已更改的行时,只需在gen上进行迭代,如下所示:

for row in gen:
   # here you use row

答案 3 :(得分:0)

您可以使用标志来检查正负。

Connect-AzAccount -TenantID xxxxx-xxx-xxx-xxxxx-xxxxx

# Creating Azure Active Directory App

$AzADAppName = "xxxxx-active-directory-app"
$AzADAppUri = "https://xxxxx.com/xxxxx-app"
$AzADAppSecret = "xxxxx"
$AzADApp = Get-AzADApplication -DisplayName $AzADAppName

if (-not $AzADApp) {
    if ($AzADApp.IdentifierUris -ne $AzADAppUri) {

        $AzADApp = New-AzADApplication -DisplayName $AzADAppName -HomePage $AzADAppUri -IdentifierUris $AzADAppUri -Password $(ConvertTo-SecureString -String $AzADAppSecret -AsPlainText -Force)
        $AzADServicePrincipal = New-AzADServicePrincipal -ApplicationId $AzADApp.ApplicationId

        # Assign the Contributor RBAC role to the service principal
        # If you get a PrincipalNotFound error: wait 15 seconds, then rerun the following until successful

        $Retries = 0; While ($NewRole -eq $null -and $Retries -le 6) {
            # Sleep here for a few seconds to allow the service principal application to become active (usually, it will take only a couple of seconds)
            Sleep 15
            New-AzRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $AzADApp.ApplicationId -ErrorAction SilentlyContinue
            $NewRole = Get-AzRoleAssignment -ServicePrincipalName $AzADServicePrincipal.ApplicationId -ErrorAction SilentlyContinue
            $Retries++;
        }

        "Application {0} Created Successfully" -f $AzADApp.DisplayName


        # Display the values for your application 
        "Save these values for using them in your application"
        "Subscription ID: {0}" -f (Get-AzContext).Subscription.SubscriptionId
        "Tenant ID:{0}" -f (Get-AzContext).Tenant.TenantId
        "Application ID:{0}" -f $AzADApp.ApplicationId
        "Application AzADAppSecret :{0}" -f $AzADAppSecret
    }
}
else {
    "Application{0} Already Exists" -f $AzADApp.DisplayName
}


# Creating Azure Resource Group

$DataFactoryName = "xxxxx-DataFactory"
$ResourceGroupName = "xxxxx-ResourceGroup"
$ResourceGroup = Get-AzResourceGroup -Name $ResourceGroupName
$Location = 'westeurope'

if (-not $ResourceGroup) {
    $ResourceGroup = New-AzResourceGroup $ResourceGroupName -location 'westeurope'
    if ($ResourceGroup) {
        "Resource Group {0} Created Successfully" -f $ResourceGroup.ResourceGroupName
    }
    else {
        "ERROR: Resource Group Creation UNSUCCESSFUL"
    }
}
else {

    "Resource Group {0} Exists" -f $ResourceGroup.ResourceGroupName 
}

# Creating Azure Data Factory

$DataFactory = Get-AzDataFactoryV2 -Name $DataFactoryName -ResourceGroupName $ResourceGroup.ResourceGroupName

if (-not $DataFactory) {
    $DataFactory = Set-AzDataFactoryV2 -ResourceGroupName $ResourceGroup.ResourceGroupName -Location $ResourceGroup.Location -Name $DataFactoryName
    if ($DataFactory) {
        "Data Factory {0} Created Successfully" -f $DataFactory.DataFactoryName
    }
    else {
        "ERROR: Data Factory Creation UNSUCCESSFUL"
    }
}
else {
    "Data Factory {0} Already Exists" -f $DataFactory.DataFactoryName 
}


# Creating Azure SQL Server and  Database
$ServerName = "xxxxx"
$DatabaseName = "xxxxx"
$AzSQLServer = Get-AzSqlServer -ServerName $ServerName

$Subscription = Get-AzSubscription

"Subscription Data" -f $Subscription.Id

if (-not $AzSQLServer) {
    "Creating New Azure SQL Server"

    $AdminSqlLogin = "xxxxx"
    $Password = "xxxxx"
    $StartIp = "xxxxx.xxxxx.xxxxx.xxxxx"
    $EndIp = "xxxxx.xxxxx.xxxxx.xxxxx"

    $AzSQLServer = New-AzSqlServer -ResourceGroupName $ResourceGroupName `
        -ServerName $ServerName `
        -Location $Location `
        -SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AdminSqlLogin, $(ConvertTo-SecureString -String $Password -AsPlainText -Force))
    if ($AzSQLServer) {  
        $FireWallRule = New-AzSqlServerFirewallRule -ResourceGroupName $ResourceGroupName `
            -ServerName $ServerName `
            -FirewallRuleName "AllowedIPs" -StartIpAddress $StartIp -EndIpAddress $EndIp
        if ($FireWallRule) {
            "Server Created Successfully {0} with firewall Rule Setup" -f $AzSQLServer.ServerName
        }
        else {
            "Server Created Successfully {0} No FireWall Setup" -f $AzSQLServer.ServerName
        }
    }
    else {
        "ERROR: Server Creation UNSUCCESSFUL"
    }

}
else {
    "Server Exists {0}" -f $AzSQLServer.ServerName
}

$AzSQLDatabase = Get-AzSqlDatabase -DatabaseName $DatabaseName -ServerName $ServerName -ResourceGroupName $ResourceGroup.ResourceGroupName

if (-not $AzSQLDatabase) {
    "Creating New Azure SQL Database" 
    $Parameters = @{
        ResourceGroupName             = $ResourceGroupName
        ServerName                    = $ServerName
        DatabaseName                  = $DatabaseName
        RequestedServiceObjectiveName = 'S0'
    }
    $AzSQLDatabase = New-AzSqlDatabase @Parameters
    if ($AzSQLDatabase) {
        "Azure SQL Database {0} Created Successfully " -f $AzSQLDatabase.DatabaseName
    }
    else {
        "ERROR: Azure SQL Database Creation UNSUCCESSFUL"
    }
}
else {
    "Database {0} Exists " -f $AzSQLDatabase.DatabaseName
}