Pandas .apply with conditional if in different columns
Pandas .apply with conditional if in different columns
我有一个数据框如下。我正在尝试检查 Liq_Factor
中是否有 nan
,如果有,则输入 1 否则除以 use/TW
。测试列中的结果。
+---+------------+------------+--------+--------+--------+
| 1 | | Liq_Factor | Zscire | Use | Tw |
| 2 | 01/10/2020 | 36.5 | 44 | 43.875 | 11.625 |
| 3 | 02/10/2020 | Nan | 43.625 | 13.625 | 33.25 |
| 4 | 03/10/2020 | 6.125 | 47.875 | 22.5 | 4.625 |
| 5 | 04/10/2020 | Nan | 34.25 | 37.125 | 36 |
| 6 | 05/10/2020 | 43.875 | 17.375 | 5.5 | 36.25 |
| 7 | 06/10/2020 | 40 | 14.125 | 21.125 | 14.875 |
| 8 | 07/10/2020 | 42.25 | 44.75 | 21.25 | 31.75 |
+---+------------+------------+--------+--------+--------+
我想知道我是否可以在
的意义上使用 .apply
DF1['Testing']=(DF1['Liq_Factor'].apply(lambda x: x=1 if pd.isna(DF1['Zscore']) else DF1['Use']/DF1['Tw'])
你能帮忙吗?
谢谢,
H
您可以使用 apply 或另一个替代方法是 numpy 的 where 函数:
df['Liq_Factor'] = np.where(df['Liq_Factor'] == np.Nan, 1, df['Use']/df['TW'])
根据您在下方的评论,您可以执行以下操作:
# create another column with the calculation
df['calc'] = (1/3)* df['ATV']/df['TW']*100000000
# create two rules (you can use one rule and then the opposite)
mask_0 = (df['calc'] < 1)
mask_1 = (df['calc'] > 1)
# change result value by condition
df.loc[mask_0, 'Liq Factor'] = df['calc']
df.loc[mask_1, 'Liq Factor'] = 1
使用下面的代码-
df['Testing']=df.apply(lambda x: 1 if x['Liq_Factor']=='Nan' else x['Use']/x['Tw'], axis=1)
根据评论部分的变化
df['Testing']=df.apply(lambda x: 1 if x['Liq_Factor']=='Nan' else min(x['Use']/x['Tw'],1), axis=1)
我有一个数据框如下。我正在尝试检查 Liq_Factor
中是否有 nan
,如果有,则输入 1 否则除以 use/TW
。测试列中的结果。
+---+------------+------------+--------+--------+--------+
| 1 | | Liq_Factor | Zscire | Use | Tw |
| 2 | 01/10/2020 | 36.5 | 44 | 43.875 | 11.625 |
| 3 | 02/10/2020 | Nan | 43.625 | 13.625 | 33.25 |
| 4 | 03/10/2020 | 6.125 | 47.875 | 22.5 | 4.625 |
| 5 | 04/10/2020 | Nan | 34.25 | 37.125 | 36 |
| 6 | 05/10/2020 | 43.875 | 17.375 | 5.5 | 36.25 |
| 7 | 06/10/2020 | 40 | 14.125 | 21.125 | 14.875 |
| 8 | 07/10/2020 | 42.25 | 44.75 | 21.25 | 31.75 |
+---+------------+------------+--------+--------+--------+
我想知道我是否可以在
的意义上使用.apply
DF1['Testing']=(DF1['Liq_Factor'].apply(lambda x: x=1 if pd.isna(DF1['Zscore']) else DF1['Use']/DF1['Tw'])
你能帮忙吗?
谢谢, H
您可以使用 apply 或另一个替代方法是 numpy 的 where 函数:
df['Liq_Factor'] = np.where(df['Liq_Factor'] == np.Nan, 1, df['Use']/df['TW'])
根据您在下方的评论,您可以执行以下操作:
# create another column with the calculation
df['calc'] = (1/3)* df['ATV']/df['TW']*100000000
# create two rules (you can use one rule and then the opposite)
mask_0 = (df['calc'] < 1)
mask_1 = (df['calc'] > 1)
# change result value by condition
df.loc[mask_0, 'Liq Factor'] = df['calc']
df.loc[mask_1, 'Liq Factor'] = 1
使用下面的代码-
df['Testing']=df.apply(lambda x: 1 if x['Liq_Factor']=='Nan' else x['Use']/x['Tw'], axis=1)
根据评论部分的变化
df['Testing']=df.apply(lambda x: 1 if x['Liq_Factor']=='Nan' else min(x['Use']/x['Tw'],1), axis=1)