我有一列包含字母數字字符的字串,如下所示:
AA128A
AA128B
AA128C
AA128D
AA128E
AA129A
AA129B
AA129C
CP100-10
CP100-11
CP100-12
CP100-13
CORSTG11A
CORSTG11B
CORSTG11
我想將每個單獨的字符分解成單獨的列,并將所有字母字符轉換為它們的 ASCII 十進制值,并保留原樣的數值。如果在爆炸值后值為空,我想用-1 替換它。
我已經能夠分解值并替換空值,但是當我嘗試使用 ord() 函式迭代這些值以轉換字母字符時,出現錯誤:
ord() 預期長度為 1 的字串,但找到了 int
即使我在 for 回圈中對資料型別創建條件分析。
import numpy as np
import pandas as pd
from sklearn.preprocessing import OrdinalEncoder
from pandas.api.types import is_string_dtype
from pandas.api.types import is_numeric_dtype
loc_df = pd.read_csv('C:\\path\\to\\file.csv',index_col=False)
# new data frame with split value columns
explode_df = loc_df["stoloc"].apply(lambda x: pd.Series(list(x)))
explode_df = explode_df.fillna(-1)
#Convert alpha characters to numeric
for char in explode_df:
if is_string_dtype(explode_df[char]):
explode_df_numeric[char] = ord(char)
else:
explode_df_numeric[char] = char
預期結果
uj5u.com熱心網友回復:
您收到該錯誤的原因是該變數char是列名,而這不是ord. 您應該改為傳遞該列中的值;你可以使用apply或map。
if is_string_dtype(explode_df[char]):
explode_df[char] = explode_df[char].apply(ord)
else:
explode_df[char] = explode_df[char]
但是您的代碼中還有其他問題。對列進行 for 回圈并檢查列的型別并不能解決問題,因為有些列同時包含字串和整數。一個簡單的解決方案是帶有檢查的applymapis_int:
def is_int(s):
try:
int(s)
return True
except:
return False
# new data frame with split value columns
explode_df = loc_df["stoloc"].apply(list).apply(pd.Series)
explode_df = explode_df.fillna(-1)
explode_df_numeric = explode_df.applymap(lambda x: x if is_int(x) else ord(x))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/390608.html
