# Populate new field based on max value

617
2
02-27-2019 03:56 AM
Esri Contributor

I am working with election data, with each row representing a district and each column represent a party. The columns have a percentage value for each party, in relation to total amount of votes in the given district. I have attached a screenshot of

my table.

Is there some way, using arcpy, that I can populate a new field with the column name of the winning party, as well as another field with the winning percentage?

An example could be the first row, where the winning party is 'A. Socialdemokratiet', with a percentage of 28,8. These two values would then be written to two new columns, say 'Winner: A. Socialdemokratiet' and 'Winner_share: 28,8'

1 Solution

Accepted Solutions
MVP Regular Contributor

You might try something like:

import arcpy

fc = r"C:\path\to\file.gdb\feature"

# add field (may want to check if they exist first)
arcpy.AddField_management(fc, "winner", "TEXT", "", "", 50,
"winner", "NULLABLE")
arcpy.AddField_management(fc, "percent", "DOUBLE", "", "", "",
"percent", "NULLABLE")

# list of fields with votes, and for winner and winning percent
fields = [ 'socialdemo', 'radikale', 'konservative', 'socialistisk', 'liberal', 'winner', 'percent' ]

with arcpy.da.UpdateCursor(fc, fields) as cursor:
for row in cursor:
votes = row[:5] # fields with vote counts or percentages

# get maximum vote / percent
# get winner / party

# other options if needed
# # if votes, you can sum them
# # and calculate percentage
# percent = float(winTotal)/vTotal

row[5] = winner   # party
row[6] = winTotal # percent
cursor.updateRow(row)‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

Hope this helps.

2 Replies
MVP Regular Contributor

You might try something like:

import arcpy

fc = r"C:\path\to\file.gdb\feature"

# add field (may want to check if they exist first)
arcpy.AddField_management(fc, "winner", "TEXT", "", "", 50,
"winner", "NULLABLE")
arcpy.AddField_management(fc, "percent", "DOUBLE", "", "", "",
"percent", "NULLABLE")

# list of fields with votes, and for winner and winning percent
fields = [ 'socialdemo', 'radikale', 'konservative', 'socialistisk', 'liberal', 'winner', 'percent' ]

with arcpy.da.UpdateCursor(fc, fields) as cursor:
for row in cursor:
votes = row[:5] # fields with vote counts or percentages

# get maximum vote / percent
# get winner / party

# other options if needed
# # if votes, you can sum them
cursor.updateRow(row)‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍