Home > Back-end >  Apply a value from column['a'] or column['b'] to column['c']
Apply a value from column['a'] or column['b'] to column['c']

Time:07-09

This is kind of a weird questions because I solved the problem but I don't know what step solved my issue:

I have 3 columns: df['sqft'], df['acres'] and df['lot_square_feet'].

I need to fill df['lot_square_feet'] with the values from df['sqft'] and df['acres']. df['sqft'] and df['acres'] will never both contain values > 0 so that does not have to be accounted for.

I've tried masking:

df['lot_square_feet'] =(df[(df['acres'].notna()) & (df['acres'] > 0)]) or (df[(df['sq1'].notna()) & (df['sq1'] > 0)])

writing custom functions:

def newcolumn(a, b, c):
    for i in range(0,len(df)):
        if df[a].iloc[i] > 0:
            return df[c].iloc[i] = df[a].iloc[i]            
        elif df[b].iloc[i] > 0:
            return df[c].iloc[i] = (df[b].iloc[i]) * 43560
        else:
            pass
df['lot_square_feet'] = df.apply(newcolumn(a='sq1', b='acres',c = 'lot_square_feet'))

Writing lambda expressions:

df['lot_square_feet'] = df[['sq1', 'acres']].apply(lambda x,y :x if x > 0 else (y if y > 0 else None))

and several other solutions over the past 2-3 hours, I kept getting errors but I just checked my dataframe and df['lot_square_feet'] has the correct amount of values and everything has been converted from acres to square feet. So obviously somthing I did worked but I have no clue what worked.

If someone has any idea what the optimal way to solve this solution is, that would be greatly appreciated. I'm pleasantly surprised but have absolutely no clue what worked and I overwrote several of the processes that I used already.

Thanks in Advance

CodePudding user response:

How about:

df['lot_square_feet'] = (df[['acres', 'sqft']] * [43560, 1]).max(axis=1)

Example:

df = pd.DataFrame({
    'sqft': [0, 1000, 0, 2000],
    'acres': [1, 0, 2, 0],
})
df['lot_square_feet'] = (df[['acres', 'sqft']] * [43560, 1]).max(axis=1)
>>> df
   sqft  acres  lot_square_feet
0     0      1            43560
1  1000      0             1000
2     0      2            87120
3  2000      0             2000
  • Related