我有一个带有文本列的 Pandas 数据框。
我想创建一个新列,其中的值以文本列中文本字符串的开头为条件。
所以如果文本列的前 30 个字符:
== 'xxx...xxx'
然后返回值 1
== 'yyy...yyy'
然后返回值 2
== 'zzz...zzz'
然后返回值 3
if none of the above return 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
关于python - 根据其他列的文本字符串的开头创建新的 pandas 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42225711/