以下の内容はhttps://a1026302.hatenablog.com/entry/2024/07/20/134345より取得しました。


【Python】Pandas の .apply() 関数に例外処理を追加する方法

Pandas の .apply() 関数に lambda の処理を入れていたのですが、1レコードでも例外が含まれていると全ての処理に影響してしまうという問題がありました。

コード

問題のコード

import pandas as pd
import numpy as np

_df=pd.DataFrame(np.array([['a','a'], [1,2]]))

try:
    _df[0].apply(lambda x: int(x)+1)

except Exception: int(x)+1
    logger.warning(f"no change.")    

改良

import pandas as pd
import numpy as np

_df=pd.DataFrame(np.array([['a','a'], [1,2]]))

def _hoge(x):
    try:
        return int(x)+1
    except:
        return 'error:' + str(x)

try: 
    _df[0].apply(lambda x: _hoge(x))
except Exception:
    logger.warning(f"no change.") 



以上の内容はhttps://a1026302.hatenablog.com/entry/2024/07/20/134345より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14