我有一个带有文本列的pandas数据框。
我想创建一个新列,其中的值以文本列中文本字符串的开头为条件。
因此,如果文本列的前30个字符:
='xxx…xxx'然后返回值1/
='yyy…yyy'然后返回值2
='zzz…zzz'然后返回值3
如果以上都不返回0

最佳答案

有可能使用多个numpy.where,但如果更多条件使用apply
对于从strats中选择字符串,请使用indexing with 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

#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

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

编辑:
如果长度不同,只需要:
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

编辑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

09-09 23:48
查看更多