亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用字典 python 的 pandas 數據框中的 StopIteration 問題

使用字典 python 的 pandas 數據框中的 StopIteration 問題

米琪卡哇伊 2023-07-27 16:02:01
我有 3 列(DM1_ID、DM2_ID、對)pandas 數據框,包含 100 萬條記錄。此外,我有一個包含鍵和多個值的字典。該函數檢查字典值并獲取鍵并將該鍵放入 new_ID 字段中。函數對于 pandas 數據幀的一小部分工作正常,但是當我將其應用于整個數據幀時,它會給我“StopIteration”錯誤。        DM1_ID      DM2_ID       pairs86503   11945.0     11945.0     [11945.0, 11945.0]86504   11945.0     362380.0    [11945.0, 362380.0]86505   11945.0     538395.0    [11945.0, 538395.0]86506   538395.0    591587.0    [11945.0, 591587.0]86507   11946.0     11946.0     [11946.0, 11946.0]86508   362380.0    200589       [362380.0,  200589.0]86509   564785.0    11946.0     [564785.0, 11946.0]f = lambda x: next(k for k,v in jdic.items() if any(i in v for i in x))jdic = {10045: [1, 6, 7,10045, 15, 45, 55, 80], 11945: [11945, 362380,20589, 10, 27, 538395, 591587], 3: [3, 21, 28, 32, 35], 11946: [11946, 39, 564785]}largeFile13000['new_ID'] = largeFile13000['pairs'].apply(f)largeFile13000.drop('pairs', axis=1, inplace=True)largeFile13000.head()# final result I'm expecting is        DM1_ID     DM2_ID        new_ID86503   11945.0    11945.0       1194586504   11945.0    362380.0      1194586505   11945.0    538395.0      1194586506   538395.0   591587.0      1194586507   11946.0    11946.0       11946  86508   362380.0   200589        1194586509   564785.0   11946.0       11946# errorStopIteration                             Traceback (most recent call last)<ipython-input-14-ddbcd19d6baa> in <module>----> 1 largeFile13000['new_ID'] = largeFile13000['pairs'].apply(f)      2 largeFile13000.drop('pairs', axis=1, inplace=True)      3 largeFile13000.head()c:\users\ravindu\appdata\local\programs\python\python37\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)   3589             else:   3590                 values = self.astype(object).values-> 3591                 mapped = lib.map_infer(values, f, convert=convert_dtype)   3592    3593         if len(mapped) and isinstance(mapped[0], Series):pandas\_libs\lib.pyx in pandas._libs.lib.map_infer()有誰可以幫我解決這個問題嗎?提前致謝。
查看完整描述

1 回答

?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

從您的數據來看,本質上您只需要查找一列,例如“DM1_ID”,因為相應的“DM2_ID”應該屬于jdic中的同一鍵。在這種情況下,這很容易做到。我只是把你的字典翻過來。


jdic = {10045: [1, 6, 7,10045, 15, 45, 55, 80], 11945: [11945, 362380,20589, 10, 27, 538395, 591587], 3: [3, 21, 28, 32, 35], 11946: [11946, 39, 564785]}


ndic = {}

for key in jdic:

    for i in jdic[key]:

        ndic[i] = key

然后應用條件。


largeFile13000['new_ID'] = largeFile13000['DM1_ID'].apply(lambda x: ndic[x])

順便說一句,我不知道你是否有什么具體原因以這種方式構建字典jdic。對于這種明顯的多對一關系,最好使用“多”方作為密鑰。


查看完整回答
反對 回復 2023-07-27
  • 1 回答
  • 0 關注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號