我正在尝试在数据帧(sdbfile)中创建一系列,其值基于使用 sdbfile 数据帧中的元素的多个嵌套条件语句。系列reins_code 填充了字符串值。
下面的语句有效,但是我需要配置为“reins_code”是否以“R”开头,而不是 == 特定的“R#”
sdbfile['product'] = np.where(sdbfile.reins_code == 'R2', 'HiredPlant','Trad')
它不喜欢字符串函数startswith(),因为它是np.series?
有人可以帮忙吗?费力地浏览了文档,但找不到对此问题的引用......
最佳答案
使用矢量化 str.startswith
返回 bool 掩码:
In [6]:
df = pd.DataFrame({'a':['R1asda','R2asdsa','foo']})
df
Out[6]:
a
0 R1asda
1 R2asdsa
2 foo
In [8]:
df['a'].str.startswith('R2')
Out[8]:
0 False
1 True
2 False
Name: a, dtype: bool
In [9]:
df[df['a'].str.startswith('R2')]
Out[9]:
a
1 R2asdsa
关于python - Numpy/Pandas 系列以运算符开头?它存在吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36583515/