使用np.argwhere()打标签问题记录与index 0 is out of bounds for axis 0 with size 0

摘要:

出现索引问题,需要先检查索引问题:

索引可能出现问题原因是:

1.自定义的列表长度不符合遍历要求

2.存在空值现象占用,需要去除空值才能进行(本文解决方式)

df.dropna( subset =['pending_cols_name'] )

问题:

IndexError: index 0 is out of bounds for axis 0 with size 0

def str2code( x:str )->int:
    '''
    pending_cols_name:等待处理的 pd.DataFrame 中的列名
    
    '''

    tempList = MyDataFrame['pending_cols_name'].unique()
    result = np.argwhere(  tempList == x )[0,0]
    return result


import swifter ## apply加速工具

%time MyDataFrame['pending_cols_name'].swifter.apply( str2code  )

 ____

其他附加问题:

import pandas as pd
import numpy as np

# 假设你有以下多个列需要处理
pending_cols_names = ['travel', 'sourceEnterpriseName', 'travelRouteAndName', 'arrivalArea', 'returnArea', 'guestArea', 'enterprisename', 'type', 'city']

def str2code(col_series):
    unique_values = col_series.unique()
    def map_str_to_index(x):
        try:
            index = np.where(unique_values == x)[0][0]
            return index
        except IndexError:
            # 当x不在unique_values中时的处理,这里假设返回NaN
            return np.nan
    return col_series.apply(map_str_to_index)

# 更新DataFrame
for col in pending_cols_names:
    MyDataFrame[f'{col}_index'] = str2code(MyDataFrame[col])

# 若需要加速处理,可以考虑使用swifter (需确保已安装并导入)
# import swifter
# for col in pending_cols_names:
#     MyDataFrame[f'{col}_index'] = MyDataFrame[col].swifter.apply(str2code)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值