0

I have a dataframe with zip codes and incomes. Some of the incomes are = 0, which is wrong.

I have a dictionary with each zip code mapped to the mean income for all incomes within that zip code.

I want to replace all of the incomes in my dataframe that = 0 with the mean income value for it's respective zip code.

I have tried this:

income = []
for row in df['income']:
    if row == 0:
        income.replace({0:{income_zip}}, inplace = True)
    else:
        income.append(row)

To no avail. I have found lots of resources to replace all 0's with the same value, I am just unsure how to replace a 0 with a variable value from a dict based on another value in the row.

3 Answers 3

1

You could also define your transformation function and use apply on your dataframe along the axis 1 (rows):

def transform(row):
    d = {'zip_code_1': 'mean_income_1', 'zip_code_2': 'mean_income_2'}
    row['income'] = d[row['zip_code']] if row['income'] == 0 else row['income']
    return row

df = df.apply(transform, axis=1)
0

Do you want to say this ?

income = []
for row in df['income']:
    if row == 0:
        df['income'].replace({0:{income_zip}}, inplace = True)
    else:
        income.append(row)
2
  • @bstrain Iterating over dataframe values is rarely the most efficient solution.
    – Andrew L
    Jul 16, 2017 at 10:16
  • Yes, I know. I am only dealing with about 17k rows and am not going for speed. I am pretty new to python in general and am just wrapping my head around getting this stuff done. I will cross the optimization bridge when I come to it.
    – bstrain
    Jul 16, 2017 at 10:20
0

Or this one-liner:

df['income'] = map(lambda x, y : y if y != 0 else income_zip[x], *[df['zip_codes'], df['income']])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.