假設我們有一個資料框,其最后一列由文字字串組成,如下所示:
df = pd.DataFrame(
{
"col1": ["C", "A", "B"],
"col2": [4, 1.7, 1],
"col3": ["SHRTYPPS", "PGYTCCCKAR", "VPCCYCCARE"],
}
)
請注意,1)字串中字符的存在和 2)它在字串中的位置都很重要。
單熱編碼最后一列如下:
col3_lst = [list(i) for i in df.col3]
ids, U = pd.factorize(np.concatenate(col3_lst))
df_new = pd.DataFrame([np.isin(U, i) for i in col3_lst], columns=U).astype(int)
pd.concat([df, df_new], axis=1).drop(["col3"], axis=1)
這將導致:
col1 col2 S H R T Y P G C K A V E
0 C 4.0 1 1 1 1 1 1 0 0 0 0 0 0
1 A 1.7 0 0 1 1 1 1 1 1 1 1 0 0
2 B 1.0 0 0 1 0 1 1 0 1 0 1 1 1
但是,正如您所見,訂單并未相應地考慮。無論如何將有關字符在相應字串中的位置的資訊注入輸出資料幀?例如,如果最后一個字串中有四個 C,我們需要捕獲字母出現在第 3、第 4、第 6 和第 7 位的事實資訊。我正在尋找類似以下的內容:
col1 col2 position_1 posistion_2 position_3 position_4 position_5 ....
0 C 4.0 19 8 18 20 25 ....
1 A 1.7 16 7 25 20 3 ....
2 B 1.0 22 16 3 3 25 ....
, 其中每個編碼列的數字標簽, $position_{i}$, 屬于英文字母表中后一個字符的位置; 即1代表A,2代表B,等等......
甚至更好,如下所示:
col1 col2 position_1_A position_1_B ... posistion_2_A posistion_2_B ... position_3_A position_3_B ... position_4_A position_4_B ...
0 C 4.0 0 0 ... 0 0 ... 0 0 ... 0 0 ...
1 A 1.7 0 0 ... 0 0 ... 0 0 ... 0 0 ...
2 B 1.0 0 0 ... 0 0 ... 0 0 ... 0 0 ...
謝謝,
uj5u.com熱心網友回復:
好的,這樣的事情應該可以解決問題:
result = df["col3"].str.upper()\
.str.extractall("(.)")\
.unstack().droplevel(0, axis=1)\
.add_prefix('position_')
result.applymap(lambda x: ord(x) - 64 if pd.notna(x) else x)
在第一步中,我們提取所有字符(我使用extractall("(.)")而不是split("")不處理其他字符 (\n)。
在第二個中,我們將字母映射到數字。
結果看起來像這樣:
match position_0 position_1 position_2 position_3 position_4 position_5 position_6 position_7 position_8 position_9
0 19 8 18 20 25 16 16 19 NaN NaN
1 16 7 25 20 3 3 3 11 1 18.0
2 22 16 3 3 25 3 3 1 18 5.0
編輯:如果你想做一個 hot_encoding 使用 pd.get_dummies()
result = df["col3"].str.upper()\
.str.extractall("(.)")\
.unstack().droplevel(0, axis=1)\
.add_prefix('position_')
pd.get_dummies(result)
這可以給你:
position_0_P position_0_S position_0_V ... position_9_R
0 0 1 0 ... 0
1 1 0 0 ... 1
2 0 0 1 ... 0
編輯2:
如果您已經將缺失編碼為.,并且您想使用序數編碼將它們編碼為缺失,則必須替換.為np.nan:
result = df["col3"].str.upper()\
.str.extractall("(.)")\
.unstack().droplevel(0, axis=1)\
.add_prefix('position_')\
.replace('.',np.nan)
其他一切都保持不變。
例如:
df = pd.DataFrame(
{
"col1": ["C", "A", "B", "D"],
"col2": [4, 1.7, 1, 12],
"col3": ["SHRTYPPS", "PGYTCCCKAR", "VPCCYCCARE", "HY.RT..CCTCC"],
}
)
result = df["col3"].str.upper().str.extractall("(.)").unstack().droplevel(0, axis=1).add_prefix('position_').replace('.',np.nan)
result.applymap(lambda x: ord(x) - 64 if pd.notna(x) else x)
#match position_0 position_1 position_2 ... position_11
#0 19 8 18.0 ... NaN
#1 16 7 25.0 ... NaN
#2 22 16 3.0 ... NaN
#3 8 25 NaN ... 3.0
pd.get_dummies(result)
# position_0_H position_0_P position_0_S position_0_V ... position_10_C position_11_C
#0 0 0 1 0 ... 0 0
#1 0 1 0 0 ... 0 0
#2 0 0 0 1 ... 0 0
#3 1 0 0 0 ... 1 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/421242.html
標籤:
