1

I have a DataFrame with yearly kg/ha values in which the columns reach from 1950 to 2015. The first column are gridcodes (gridcode_1) reaching from 1 to 4. Every gridcode has a specific addition value I want to add to the kg/ha values of the other columns.

I tried to solve it via for loop and regular expression

for x in kilograms_dep2:
    if kilograms_dep2['gridcode_1'] == 1:
        kilograms[regex="[0-9]{4}"] + 2.7
    elif kilograms_dep2['gridcode_1'] == 2:
        kilograms_dep2[regex="[0-9]{4}"] + 16.04
    elif kilograms_dep2['gridcode_1'] == 3:
        kilograms_dep2[regex="[0-9]{4}"] + 2.7
    elif kilograms_dep2['gridcode_1'] == 4:
        kilograms_dep2[regex="[0-9]{4}"] + 0.75

but it would only result in syntax errors.

Here are the first few entries of the dataframe

 gridcode_1         1950_y         1951_y         1952_y         1953_y
          1    1477.273256    1477.273256    1477.273256    1477.273256
          2  523883.351859  523883.351859  523883.351859  523883.351859
          3    2698.864601    2698.864601    2698.864601    2698.864601
          4    6458.175014    6458.175014    6458.175014    6458.175014

so for gricode_1 = 1 I want to add 2.7, for gridcode_1 = 2 I want to add 16.04 etc.

I'd appreciate every help for an elegant solution.

1 Answer 1

1
columns_list  = list(df.columns)
columns_list.remove('code')

df.loc[(df['code'] == 1 ),columns_list] = df.loc[(df['code'] == 1),columns_list] + 2.7

df.loc[(df['code'] == 2 ),columns_list] = df.loc[(df['code'] == 2),columns_list] + 16.04

result:

Result

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.