摘要:
出现索引问题,需要先检查索引问题:
索引可能出现问题原因是:
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)