将列 ['a'] 或列 ['b'] 中的值应用于列 ['c']



这是一个奇怪的问题,因为我解决了这个问题,但我不知道哪一步解决了我的问题:

我有3列:df['sqft'], df['acres']和df['lot_square_feet']。

我需要用df['sqft']和df['acres']的值填充df['lot_square_feet']。Df ['sqft']和Df ['acres']不会同时包含值>

我试过屏蔽:

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

编写自定义函数:

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'))

写lambda表达式:

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

和其他几个解决方案在过去的2-3小时,我一直得到错误,但我只是检查了我的数据框架和df['lot_square_feet']有正确的数值,一切都从英亩转换为平方英尺。所以很明显,我做了一些工作,但我不知道是什么工作。

如果有人知道解决这个问题的最佳方法是什么,我将不胜感激。我很惊喜,但完全不知道什么是有效的,我重写了几个我已经使用过的进程。

Thanks in Advance

如何:

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

的例子:

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

最新更新