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

标签 python string pandas conditional-statements startswith

我有一个带有文本列的 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/

相关文章:

python - 将 Maya 模块导入 Nuke (Python)

python - 使用 C 扩展或 Cython 优化非平凡 Python 应用程序的教程

PHP快速随机字符串函数

r - 从R中的字符串中提取数字

python - Pandas :FutureWarning:改为使用 pd.to_datetime

pandas - matplotlib.axis.axes mplfinance 体积误差

python - 如何禁用 pywebkit 控制台消息?

C# 最长常用词示例

python - 如何计算 Pandas Dataframe 中所有列的哈希值?

python - 如何将 Seaborn 图保存到文件中