我有这个数据框
name year ...
0 Carlos - xyz 2019
1 Marcos - yws 2031
3 Fran - xxz 2431
4 Matt - yre 1985
...
我想创建一个名为 type 的新列。 如果人名以“xyz”或“xxz”结尾,我希望类型为“big”
所以,它应该看起来像这样:
name year type
0 Carlos - xyz 2019 big
1 Marcos - yws 2031
3 Fran - xxz 2431 big
4 Matt - yre 1985
...
有什么建议吗?
最佳答案
选项 1
使用 str.contains
生成掩码:
m = df.name.str.contains(r'x[yx]z$')
或者,
sub_str = ['xyz', 'xxz']
m = df.name.str.contains(r'{}$'.format('|'.join(sub_str)))
现在,您可以使用 np.where
创建列,
df['type'] = np.where(m, 'big', '')
或者,loc
代替 np.where
;
df['type'] = ''
df.loc[m, 'type'] = 'big'
df
name year type
0 Carlos - xyz 2019 big
1 Marcos - yws 2031
3 Fran - xxz 2431 big
4 Matt - yre 1985
选项 2
作为替代方案,请考虑 str.endswith
+ np.ological_or.reduce
sub_str = ['xyz', 'xxz']
m = np.logical_or.reduce([df.name.str.endswith(s) for s in sub_str])
df['type'] = ''
df.loc[m, 'type'] = 'big'
df
name year type
0 Carlos - xyz 2019 big
1 Marcos - yws 2031
3 Fran - xxz 2431 big
4 Matt - yre 1985
关于python - 按字符串列中最后 3 个字符选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49524245/