简体   繁体   中英

Pandas two dataframes for loop: how to set value to old value + 1

There are two dataframe roads and bridges .

If the kilometre point of a bridge falls between the chainage begin and end of a road segment, it should be checked which condition this bridge is in (this is A, B, C or D).

If the condition is 'A' (this is a string) --> then in the roads df, the value under the column name 'BridgeA' should become the old value + 1 .

In the end, this column will show how many bridges of condition A a road segment contains.

The code we've written for this runs. However, it results in only zero's in the columns BridgeA, BridgeB, BridgeC and BridgeD.

Can someone help us out what is going wrong?

for j in roads.index: # loop through all the rows in the roads file

    for i in bridges.index: # for every line in the bridges file
        if bridges.km[i] > roads.Chainage_begin.loc[j] and \
        bridges.km[i] < roads.Chainage_end.loc[j]: # if the bridge falls within the road segment

            if bridges.condition[i] == 'A':
                roads.BridgeA.loc[j] =+ 1
            elif bridges.condition[i] == 'B':
                roads['BridgeB'].loc[j] =+ 1
            elif bridges.condition[i] == 'C':
                roads['BridgeC'].loc[j] =+ 1
            elif bridges.condition[i] == 'D':
                roads['BridgeD'].loc[j] =+ 1

        else: # if it is out of range
            continue # go on to the next row in the roads file

You should never use df.column[row_index] nor df[column][row_index] . It works when you read a value but is error prone when you try to set a value. The only robust syntax is

df.loc[row_index, col] = ...

So here you should use:

        if bridges.condition[i] == 'A':
            roads.loc[j, 'BridgeA'] += 1
        elif bridges.condition[i] == 'B':
            roads.loc[j, 'BridgeB'] += 1
        elif bridges.condition[i] == 'C':
            roads.loc[j, 'BridgeC'] += 1
        elif bridges.condition[i] == 'D':
            roads.loc[j, 'BridgeD'] += 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM