我想通過檢查“A”列的第一個和第三個位置中的字符是否與“B”列的第一個和第三個位置中的字符匹配來創建兩個二進制指示符。
這是一個示例資料框:
df = pd.DataFrame({'A' : ['a%d', 'a%', 'i%'],
'B' : ['and', 'as', 'if']})
A B
0 a%d and
1 a% as
2 i% if
我希望資料框如下所示:
A B Match_1 Match_3
0 a%d and 1 1
1 a% as 1 0
2 i% if 1 0
我嘗試使用以下字串比較,但該列只為 match_1 列回傳“0”值。
df['match_1'] = np.where(df['A'][0] == df['B'][0], 1, 0)
我想知道是否有一個類似于 SQL 中找到的 substr 函式的函式。
uj5u.com熱心網友回復:
您可以使用 pandasstr方法,該方法可以對元素進行切片:
df['match_1'] = df['A'].str[0].eq(df['B'].str[0]).astype(int)
df['match_3'] = df['A'].str[2].eq(df['B'].str[2]).astype(int)
輸出:
A B match_1 match_3
0 a%d and 1 1
1 a% as 1 0
2 i% if 1 0
如果要測驗的位置很多,可以使用回圈:
for pos in (1, 3):
df['match_%d' % pos] = df['A'].str[pos-1].eq(df['B'].str[pos-1]).astype(int)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/337491.html
