我试图在我的dataframe ( sdbfile )中创建一个系列,它的值基于几个嵌套的条件语句,使用来自sdbfile dataframe的元素。系列reins_code中填充了字符串值。
然而,下面的声明是有效的,但我需要配置它来说明“reins_code”是否以“R”开头,而不是==以特定的“R#”开头。
sdbfile['product'] = np.where(sdbfile.reins_code == 'R2', 'HiredPlant','Trad')它不喜欢字符串函数startswith()作为np.series?
有人能帮忙吗?已涉猎过文件,但看不到对此问题的引用.
发布于 2016-04-12 21:32:45
使用向量化的str.startswith返回布尔掩码:
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发布于 2016-04-12 21:01:27
使用熊猫str属性。http://pandas.pydata.org/pandas-docs/stable/text.html
序列和索引都配备了一组字符串处理方法,可以方便地对数组的每个元素进行操作。也许最重要的是,这些方法自动排除丢失的/NA值。它们通过str属性访问,通常具有与等效(标量)内置字符串方法匹配的名称:
sdbfile['product'] = np.where(sdbfile.reins_code.str[0] == 'R', 'HiredPlant','Trad')https://stackoverflow.com/questions/36583515
复制相似问题