根据其他列的文本字符串开头创建新的pandas列

Pie*_*rre 4 python string startswith conditional-statements pandas

我有一个带有文本列的pandas数据框。

我想创建一个新列,其中的值取决于text列中文本字符串的开头。

因此,如果text列的前30个字符是:

=='xxx ... xxx'然后返回值1 /

=='yyy ... yyy'然后返回值2

=='zzz ... zzz'然后返回值3

如果以上都不返回0

jez*_*ael 5

可以使用多个,numpy.where但如果有更多条件,请使用apply

对于来自strat的选择字符串,请使用带有str的索引

df = pd.DataFrame({'A':['xxxss','yyyee','zzzswee','sss'],
                   'B':[4,5,6,8]})

print (df)
         A  B
0    xxxss  4
1    yyyee  5
2  zzzswee  6
3      sss  8
Run Code Online (Sandbox Code Playgroud)
#check first 3 values
a = df.A.str[:3]
df['new'] = np.where(a == 'xxx', 1, 
            np.where(a == 'yyy', 2, 
            np.where(a == 'zzz', 3, 0)))

print (df)
         A  B  new
0    xxxss  4    1
1    yyyee  5    2
2  zzzswee  6    3
3      sss  8    0
Run Code Online (Sandbox Code Playgroud)
def f(x):
    #print (x)
    if x == 'xxx':
        return 1
    elif x == 'yyy':
        return 2
    elif x == 'zzz':
        return 3
    else:
        return 0

df['new'] = df.A.str[:3].apply(f)
print (df)
         A  B  new
0    xxxss  4    1
1    yyyee  5    2
2  zzzswee  6    3
3      sss  8    0
Run Code Online (Sandbox Code Playgroud)

编辑:

如果长度不同,则只需要:

df['new'] = np.where(df.A.str[:3] == 'xxx', 1, 
            np.where(df.A.str[:2] == 'yy', 2, 
            np.where(df.A.str[:1] == 'z', 3, 0)))

print (df)
         A  B  new
0    xxxss  4    1
1    yyyee  5    2
2  zzzswee  6    3
3      sss  8    0
Run Code Online (Sandbox Code Playgroud)

编辑1:

感谢您的想法Quickbeam2k1使用str.startswith每个字符串的开始检查:

df['new'] = np.where(df.A.str.startswith('xxx'), 1, 
            np.where(df.A.str.startswith('yy'), 2, 
            np.where(df.A.str.startswith('z'), 3, 0)))

print (df)
         A  B  new
0    xxxss  4    1
1    yyyee  5    2
2  zzzswee  6    3
3      sss  8    0
Run Code Online (Sandbox Code Playgroud)