python 如何在dataframe中编写跨多个列的条件语句?

zd287kbt  于 2022-11-21  发布在  Python
关注(0)|答案(1)|浏览(146)

我有以下Pandas数据框:

我正在尝试写一些条件python语句,其中如果我们有10issue_status40 AND market_phase0 AND ``的tade_state(这是我们在上面截图中所有情况下都有的),那么我想调用一个名为resolve_collision_mp(...)的函数。
我可以用Python编写如下条件吗?

# Collision for issue_status == 10
if market_info_df['issue_status'].eq('10').all() and market_info_df['market_phase'].eq('0').all() \
        and market_info_df['trading_state'] == '  ': # need to change this, can't have equality for dataframe, need loc[...]
    return resolve_collision_mp_10(market_info_df)

# Collision for issue_status == 40
if market_info_df['issue_status'].eq('40').all() and market_info_df['market_phase'].eq('0').all() \
        and not market_info_df['trading_state']:
    return resolve_collision_mp_40(market_info_df)

我不认为以上是正确的,任何帮助将不胜感激!

wooyq4lh

wooyq4lh1#

您可以使用.apply()与相关条件、

df['new_col'] = df.apply(lambda row: resolve_collision_mp_10(row) if (row['issue_status'] == 10 and row['market_phase'] == 0 and row['tade_state'] = '') else None, axis=1)

df['new_col'] = df.apply(lambda row: resolve_collision_mp_40(row) if (row['issue_status'] == 40 and row['market_phase'] == 0 and row['tade_state'] = '') else None, axis=1)

注意:我假设您尝试使用resolve_collision_mp_10resolve_collision_mp_40函数的返回值创建一个新列。

相关问题